$setField
运算符用于在嵌入文档中添加、更新或删除字段。 操作员允许精确作文档字段,这使得它可用于更新嵌套字段、重组文档甚至完全删除字段等任务。
语法
{
$setField: {
field: <fieldName>,
input: <expression>,
value: <expression>
}
}
参数
参数 | Description |
---|---|
<field> |
要转换为键值对数组的文档(对象)。 |
<input> |
正在处理的文档或字段。 |
<value> |
要分配给字段的新值。 如果 value 是 null ,则删除该字段。 |
示例
示例 1:更新嵌套字段
此查询对与特定 _id
匹配的文档的促销事件中的嵌套折扣值执行条件更新。
db.stores.updateOne(
{ "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4" },
[
{
$set: {
"store.promotionEvents": {
$map: {
input: "$store.promotionEvents",
as: "event",
in: {
$setField: {
field: "discounts",
input: "$$event",
value: {
$map: {
input: "$$event.discounts",
as: "discount",
in: {
$cond: {
if: { $eq: ["$$discount.categoryName", "Laptops"] },
then: {
categoryName: "$$discount.categoryName",
discountPercentage: 18
},
else: "$$discount"
}
}
}
}
}
}
}
}
}
}
]
)
示例 2:删除字段
假设你想要从 totalStaff
对象中删除 staff
字段。
db.collection.updateOne(
{ "store.storeId": "12345" },
[{
$set: {
"store.staff": {
$setField: {
field: "totalStaff",
input: "$store.staff",
value: null
}
}
}
}]
)
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。