0
0
MongoDBquery~30 mins

Upsert behavior (update or insert) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Upsert Behavior (Update or Insert) in MongoDB
📖 Scenario: You are managing a small online bookstore's inventory using MongoDB. You want to keep track of books and their stock counts. Sometimes you receive new books, and sometimes you get more copies of existing books. You want to write a query that updates the stock count if the book already exists, or inserts a new book if it does not.
🎯 Goal: Build a MongoDB query that uses upsert behavior to update the stock count of a book if it exists, or insert a new book document if it does not.
📋 What You'll Learn
Create a collection named books with initial book documents.
Define a filter to find a book by its title.
Write an updateOne query with upsert: true option.
Update the stock field or insert a new book document.
💡 Why This Matters
🌍 Real World
Inventory management systems often need to update existing records or add new ones seamlessly. Upsert queries help keep data accurate without extra checks.
💼 Career
Database developers and backend engineers use upsert operations to efficiently maintain data integrity and reduce code complexity.
Progress0 / 4 steps
1
Create the initial books collection with two book documents
Create a variable called books and assign it an array with two objects. The first object should have title as "The Great Gatsby" and stock as 3. The second object should have title as "1984" and stock as 5.
MongoDB
Need a hint?

Use a list of dictionaries with exact keys and values as shown.

2
Define a filter to find a book by its title
Create a variable called filter and assign it an object with the key title and the value "The Great Gatsby".
MongoDB
Need a hint?

The filter is a dictionary with the key title and the exact value.

3
Write an updateOne query with upsert: true option to update the stock
Create a variable called update and assign it an object with the key $set and value an object that sets stock to 10.
MongoDB
Need a hint?

Use the $set operator to update the stock field.

4
Complete the upsert operation with updateOne and upsert: true
Create a variable called options and assign it an object with upsert set to true. Then create a variable called result and assign it the call to db.books.updateOne(filter, update, options).
MongoDB
Need a hint?

Use the upsert: true option to insert if the book does not exist.