使用更新操作符
在这一步骤中,你将探索 MongoDB 的强大更新操作符,这些操作符允许你执行复杂的文档修改,而不仅仅是简单的值更改。
首先,让我们创建一些示例数据以便操作:
db.products.insertMany([
{
name: "Laptop",
price: 1000,
tags: ["electronics", "computer"],
stock: 50
},
{
name: "Smartphone",
price: 800,
tags: ["electronics", "mobile"],
stock: 30
}
])
MongoDB 提供了多种强大的更新操作符,允许你以复杂的方式修改文档:
$mul
操作符 - 乘以数值
db.products.updateOne(
{ name: "Laptop" },
{ $mul: { price: 1.1 } }
)
输出:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0,
upsertedId: null
}
$mul
操作符将字段的值乘以指定的数字。在这个例子中,我们将笔记本电脑的价格提高了 10%。
$push
操作符 - 向数组中添加元素
db.products.updateOne(
{ name: "Smartphone" },
{ $push: { tags: "sale" } }
)
输出:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0,
upsertedId: null
}
$push
操作符向数组字段中添加一个元素。在这里,我们向智能手机的标签中添加了一个 "sale" 标签。
$min
和 $max
操作符 - 基于比较进行更新
db.products.updateOne(
{ name: "Laptop" },
{
$min: { stock: 40 },
$max: { price: 1200 }
}
)
输出:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0,
upsertedId: null
}
$min
如果指定值小于现有值,则更新字段
$max
如果指定值大于现有值,则更新字段
让我们验证我们的更新:
db.products.find()
[
{
_id: ObjectId('674683aebec38876f7c1c18e'),
name: 'Laptop',
price: 1200,
tags: [ 'electronics', 'computer' ],
stock: 40
},
{
_id: ObjectId('674683aebec38876f7c1c18f'),
name: 'Smartphone',
price: 800,
tags: [ 'electronics', 'mobile', 'sale' ],
stock: 30
}
]
你应该会看到修改后的文档,其中价格、标签和库存水平均已更新。