0
0
MongoDBquery~30 mins

$push operator for adding to arrays in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$push Operator to Add Items to Arrays in MongoDB
📖 Scenario: You are managing a simple online bookstore database. Each book document has a title and an array of reviews. You want to add new reviews to the books as customers submit them.
🎯 Goal: Build a MongoDB update operation using the $push operator to add new review entries to the reviews array of a book document.
📋 What You'll Learn
Create a collection named books with one book document containing a title and an empty reviews array.
Define a new review object with user and comment fields.
Use the $push operator to add the new review to the reviews array of the book.
Complete the update command to modify the correct book document by its title.
💡 Why This Matters
🌍 Real World
Adding user-generated content like reviews or comments to documents is common in many applications such as e-commerce, blogs, and social media.
💼 Career
Understanding how to update array fields in MongoDB documents is essential for backend developers working with NoSQL databases.
Progress0 / 4 steps
1
Create the books collection with one book document
Create a collection called books and insert one document with title set to 'Learn MongoDB' and an empty array reviews.
MongoDB
Need a hint?

Use insertOne to add a document with the specified fields.

2
Define a new review object
Create a variable called newReview that holds an object with user set to 'Alice' and comment set to 'Great book!'.
MongoDB
Need a hint?

Use const newReview = { user: 'Alice', comment: 'Great book!' } to define the review.

3
Use $push to add the review to the book's reviews array
Write an update command using db.books.updateOne to find the book with title equal to 'Learn MongoDB' and use $push to add newReview to the reviews array.
MongoDB
Need a hint?

Use updateOne with a filter and {$push: { reviews: newReview }} to add the review.

4
Complete the update command with options
Add the option { upsert: false } as the third argument to updateOne to ensure no new document is created if the book is not found.
MongoDB
Need a hint?

Pass { upsert: false } as the third argument to updateOne.