0
0
MongoDBquery~30 mins

$min and $max update operators in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Using $min and $max Update Operators in MongoDB
📖 Scenario: You are managing a MongoDB collection that stores information about products in a store. Each product has a price field. You want to update the prices so that they never go below a certain minimum price or above a certain maximum price.
🎯 Goal: Learn how to use the $min and $max update operators in MongoDB to adjust product prices to stay within specified limits.
📋 What You'll Learn
Create a MongoDB collection named products with specific product documents.
Define minimum and maximum price limits as variables.
Use the $min operator to update product prices only if the new price is lower than the current price.
Use the $max operator to update product prices only if the new price is higher than the current price.
💡 Why This Matters
🌍 Real World
Retail stores often need to adjust product prices to stay competitive or maintain profit margins. Using $min and $max operators helps automate price adjustments safely.
💼 Career
Database administrators and backend developers use MongoDB update operators like $min and $max to maintain data integrity and enforce business rules on data.
Progress0 / 4 steps
1
Create the products collection with initial data
Create a MongoDB collection called products and insert these exact documents: { _id: 1, name: "Pen", price: 10 }, { _id: 2, name: "Notebook", price: 20 }, and { _id: 3, name: "Eraser", price: 5 }.
MongoDB
Need a hint?

Use db.products.insertMany() to add multiple documents at once.

2
Define minimum and maximum price limits
Create two variables called minPrice and maxPrice and set them to 8 and 18 respectively.
MongoDB
Need a hint?

Use const to create variables for the price limits.

3
Use $min to lower prices only if new price is less
Write an update command using db.products.updateMany() that uses the $min operator to set the price to minPrice only if minPrice is less than the current price.
MongoDB
Need a hint?

Use updateMany with an empty filter {} to update all documents.

4
Use $max to raise prices only if new price is more
Write an update command using db.products.updateMany() that uses the $max operator to set the price to maxPrice only if maxPrice is greater than the current price.
MongoDB
Need a hint?

Use updateMany again with $max to raise prices where needed.