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

In this tutorial, I explored MongoDB, a NoSQL database, to learn how to store, query, and analyze data. I worked with a sample dataset of business reviews and performed common operations like insertion, aggregation, search, update, and deletion.

Step 1: Setup MongoDB:
I installed MongoDB Compass and connected to my local database. Here’s how the dashboard looks:

Step 2: Insert Sample Data
I inserted 10 sample business reviews manually into the collection using Compass in JSON mode. Here are the documents:[
{ “business_id”: 1, “name”: “Cafe One”, “rating”: 4, “review”: “Good food and service” },
{ “business_id”: 2, “name”: “Pizza Place”, “rating”: 5, “review”: “Excellent pizza, good staff” },
{ “business_id”: 3, “name”: “Tea Corner”, “rating”: 3, “review”: “Average taste but good location” },
{ “business_id”: 4, “name”: “Burger Hub”, “rating”: 2, “review”: “Not good, very slow service” },
{ “business_id”: 5, “name”: “Sushi World”, “rating”: 5, “review”: “Fresh sushi, good experience” },
{ “business_id”: 6, “name”: “Taco House”, “rating”: 4, “review”: “Good tacos and friendly staff” },
{ “business_id”: 7, “name”: “Pasta Point”, “rating”: 3, “review”: “Average pasta but good ambience” },
{ “business_id”: 8, “name”: “Biryani Express”, “rating”: 5, “review”: “Good biryani, loved it” },
{ “business_id”: 9, “name”: “Coffee Bar”, “rating”: 4, “review”: “Good coffee, nice place to relax” },
{ “business_id”: 10, “name”: “Ice Cream Land”, “rating”: 5, “review”: “Very good flavors and service” }
]

Step 3: Running Queries
3.1 Top 5 Businesses with Highest Average Rating

Aggregation query:
[
{ “$group”: { “_id”: “$business_id”, “avgRating”: { “$avg”: “$rating” } } },
{ “$sort”: { “avgRating”: -1 } },
{ “$limit”: 5 }
]

Explanation:

I used an aggregation pipeline to group by business_id and calculate the average rating, then sorted descending to find the top 5.

3.2 Count Reviews Containing “Good”
Filter query:
{ “review”: { “$regex”: “good”, “$options”: “i” } }

Explanation:
Using a regex filter, I found all reviews containing the word ‘good’ (case-insensitive).

3.3 Get Reviews for a Specific Business
Query example for business_id = 2:
{ “business_id”: 2 }

Explanation:

This query retrieves all reviews for a specific business.

3.4 Update a Review
Query example:
{ “$set”: { “review”: “Updated review: Really good service and tasty food!” } }

Explanation:
I updated the review for business_id = 1 to reflect a more detailed feedback.

3.5 Delete a Record


Explanation:
I deleted one record from the collection to demonstrate the deletion operation.

Similar Posts