我有一个类似的事件集合:
{title: "Some Title", description: "Some Description", products: [{_id: "owkaowakdowakd", quantity: 15}]}
我想向产品数组的所有元素添加一个带有空数组的“保留”字段。要获得此结果:
{title: "Some Title", description: "Some Description", products: [{_id: "owkaowakdowakd", quantity: 15, reserved: [] }]}
查看文档,您可以使用$ []运算符对数组的所有元素进行更改。 https://docs.mongodb.com/manual/reference/operator/update/positional-all/#positional-update-all
db.events.updateMany( {"products.reserved": {$exists: false}}, {$set: {"products.$[].reserved": []}})
但这会返回一个错误:
2019-12-17T16:03:43.399+0000 E QUERY [js] WriteError({
"index" : 0,
"code" : 28,
"errmsg" : "Cannot create field 'reserved' in element {0: null}",
"op" : {
"q" : {
"products.reserved" : {
"$exists" : false
}
},
"u" : {
"$set" : {
"products.$[].reserved" : [ ]
}
},
"multi" : true,
"upsert" : false
}
}) :
WriteError({
"index" : 0,
"code" : 28,
"errmsg" : "Cannot create field 'reserved' in element {0: null}",
"op" : {
"q" : {
"products.reserved" : {
"$exists" : false
}
},
"u" : {
"$set" : {
"products.$[].reserved" : [ ]
}
},
"multi" : true,
"upsert" : false
}
})
我也试图修改每个元素的数量,因为它已经存在,但是返回相同的错误! “无法创建字段“数量” ...”