DEV Community

Aadhitya Dev
Aadhitya Dev

Posted on

MongoDB Hands-On Practice: CRUD Operations with the MongoDB Node.js Driver

You've got data, and you've got MongoDB Atlas. Now what? The best way to learn is by doing. In this tutorial, we'll take a provided dataset of business reviews and use the MongoDB Node.js driver to perform essential Create, Read, Update, and Delete (CRUD) operations.

1. Prerequisites: Connect to Your Atlas Cluster

First, we need to connect our Node.js application to MongoDB Atlas.

1.Install the driver: npm install mongodb

2.Get your connection string from your Atlas cluster dashboard (under the "Connect" button).

3.Set up your connection: Create a database.js module.

_2. The Queries (Using the Node.js Driver)
_

A. Insert the Provided Records
We'll write a script to insert your 10 review documents.

B. Query to find top 5 businesses with highest average rating.
Since each document is a single review, we need to $group by the business to calculate the average. We'll group by both business_id and name to get a clear result.

Expected Output:

C. Query to count how many reviews contain the word “good”.
We'll use the $regex operator for a case-insensitive text search on the review field. The $count stage is perfect for this.

D. Query to get all reviews for a specific business ID.
This is a simple find query. We'll find all documents where business_id matches our target.

E. Update a review and delete a record.
Update a Review:
Let's find the review for "Tech Cafe" and update its rating and text.

F.Delete a Record:
Let's delete the review for "Burger Town".


_
Conclusion_

You've now successfully performed all the requested operations on your flat reviews collection! The key difference in this approach is that business information (like the name) is duplicated in each review, which is a common trade-off for read performance and simplicity.

Key MongoDB concepts we used:

  • insertMany(): For bulk inserting documents.
  • Aggregation Pipeline ($group, $sort, $limit, $count, $match): The powerhouse for complex data analysis and transformation.
  • $regex: For powerful pattern matching within string fields.
  • find(): The standard workhorse for querying documents.
  • updateOne() and deleteOne(): For modifying and removing documents.

This hands-on approach should give you the confidence to start building your own MongoDB-backed applications. Happy coding

Top comments (0)