Use Update Operators
In this step, you'll explore powerful MongoDB update operators that allow you to perform complex document modifications beyond simple value changes.
First, let's start the MongoDB shell and ensure we're in the right database:
mongosh
use mylab_database
Let's first create some sample data to work with:
db.products.insertMany([
{
name: "Laptop",
price: 1000,
tags: ["electronics", "computer"],
stock: 50
},
{
name: "Smartphone",
price: 800,
tags: ["electronics", "mobile"],
stock: 30
}
])
MongoDB provides several powerful update operators that allow you to modify documents in sophisticated ways:
$mul
Operator - Multiply Numeric Values
db.products.updateOne(
{ name: "Laptop" },
{ $mul: { price: 1.1 } }
)
The output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0,
upsertedId: null
}
The $mul
operator multiplies the value of a field by the specified number. In this example, we're increasing the laptop's price by 10%.
$push
Operator - Add Elements to an Array
db.products.updateOne(
{ name: "Smartphone" },
{ $push: { tags: "sale" } }
)
The output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0,
upsertedId: null
}
The $push
operator adds an element to an array field. Here, we're adding a "sale" tag to the smartphone's tags.
$min
and $max
Operators - Update Based on Comparison
db.products.updateOne(
{ name: "Laptop" },
{
$min: { stock: 40 },
$max: { price: 1200 }
}
)
The output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0,
upsertedId: null
}
$min
updates the field if the specified value is less than the existing value
$max
updates the field if the specified value is greater than the existing value
Let's verify our updates:
db.products.find()
You should see the modified documents with updated prices, tags, and stock levels.