[英]How to update multiple objects in the array in mongoDB?
How to update multiple objects in the array in MongoDB?如何更新MongoDB中数组中的多个对象? Assume that I am retrieving from the client an array of titles that need to be changed.假设我正在从客户端检索需要更改的标题数组。
Example:例子:
Data from client:来自客户的数据:
[0,3]
Document in the MongoDB: MongoDB 中的文档:
[
{
_id: 0,
dishes: [
{ title: 0, in_stock: true },
{ title: 1, in_stock: false },
{ title: 2, in_stock: true },
{ title: 3, in_stock: false },
],
},
];
The result should be:结果应该是:
[
{
_id: 0,
dishes: [
{ title: 0, in_stock: false },
{ title: 1, in_stock: false },
{ title: 2, in_stock: true },
{ title: 3, in_stock: true },
],
},
];
You can simply put a aggregation pipeline in your update clause.您可以简单地在更新子句中放置一个聚合管道。
db.collection.update({},
[
{
"$addFields": {
"dishes": {
"$map": {
"input": "$dishes",
"as": "d",
"in": {
"$cond": {
"if": {
"$in": [
"$$d.title",
[
0,
3
]
]
},
"then": {
title: "$$d.title",
in_stock: {
"$not": [
"$$d.in_stock"
]
}
},
"else": "$$d"
}
}
}
}
}
}
])
Here is the Mongo playground for your reference.这是Mongo 游乐场供您参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.