Hands-On with MongoDB: Storing, Querying & Analyzing Data



This content originally appeared on DEV Community and was authored by Sri Vardhan

MongoDB is one of the most popular NoSQL databases.
In this blog, I’ll walk you through how I used MongoDB Compass to insert data, run queries, and perform analysis.

Step 1: Install MongoDB
->I installed MongoDB Community Server and MongoDB Compass for GUI interaction.

Step 2: Create Database & Collection
->Created database: mydb
->Created collection: reviews

Inserted 10 documents manually:
{ “business_id”: 1, “name”: “Pizza Point”, “review”: “The pizza was good”, “rating”: 4 }
{ “business_id”: 2, “name”: “Book World”, “review”: “Good variety of books”, “rating”: 5 }

Step 3: Top 5 Businesses by Average Rating
Using the Aggregations tab:
// Stage 1: Group
{
“$group”: {
“_id”: “$business_id”,
“name”: { “$first”: “$name” },
“avgRating”: { “$avg”: “$rating” }
}
}

// Stage 2: Sort
{ “avgRating”: -1 }

// Stage 3: Limit
{ “$limit”: 5 }

Step 4: Find Reviews Containing “good”
In the Filter bar:
{ “review”: { “$regex”: “good”, “$options”: “i” } }

Step 5: Query Reviews for a Specific Business
{ “business_id”: 2 }

Step 6: Update a Review
{ “business_id”: 2 },
{ “$set”: { “review”: “Excellent variety of books” } }

Step 7: Delete a Record
->Before deletion

->After deletion

Step 8: Export Query Results
In Compass → Aggregations → Export → JSON/CSV
Example: exported top 5 businesses as JSON.
[{
“_id”: {
“$oid”: “68c1aa6ed8d3811853f084ec”
},
“business_id”: 1,
“name”: “Cafe Delight”,
“rating”: 4,
“review”: “good coffee and snacks”
},
{
“_id”: {
“$oid”: “68c1aa6ed8d3811853f084ed”
},
“business_id”: 2,
“name”: “Food Haven”,
“rating”: 5,
“review”: “excellent food and good staff”
},
{
“_id”: {
“$oid”: “68c1aa6ed8d3811853f084ee”
},
“business_id”: 3,
“name”: “Tech Store”,
“rating”: 3,
“review”: “service improved a lot, very good now”
},
{
“_id”: {
“$oid”: “68c1aa6ed8d3811853f084ef”
},
“business_id”: 4,
“name”: “Book World”,
“rating”: 5,
“review”: “good collection of books”
},
]

Conclusion
This was a quick walkthrough of MongoDB basics using Compass:
->Inserted documents
->Ran queries
->Aggregated results
->Updated & deleted records
->Exported JSON/CSV
MongoDB Compass makes working with data super easy without needing to memorize all commands.


This content originally appeared on DEV Community and was authored by Sri Vardhan