{
_id:'1',
name:'apple',
option:[{
weight:'10',
size:'40'
price:'40',
},
{weight:'40',
size:'40'
price:'200'}]
}
如果重量或大小不同,我想在数组中插入新对象,如果大小和重量都匹配,我想更新它。我该怎么做?
最佳答案
类似于your previous question , 你使用 .bulkWrite()
但由于数组元素选择具有“多个条件”,因此您可以在此处使用 $elemMatch
:
db.collection.bulkWrite([
{ "updateOne": {
"filter": {
"_id": "1",
"option": {
"$elemMatch": { "weight": "40", "size": "40" }
}
},
"update": {
"$set": { "option.$.price": "300" }
}
}},
{ "updateOne": {
"filter": {
"_id": "1",
"option": {
"$not": {
"$elemMatch": { "weight": "40", "size": "40" }
}
}
},
"update": {
"$push": { "option": { "weight": "40", "size": "40", "price": "300" } }
}
}},
{ "updateOne": {
"filter": { "_id": 1 },
"update": {
"$setOnInsert": {
"option": [
{ "weight": "40", "size": "40", "price": "300" }
]
}
},
"upsert": true
}}
])
所以操作是:
测试
$elemMatch
中的数组元素匹配条件存在然后$set
匹配值。测试数组元素为
$not
存在于否定中。您也可以使用$ne
在每个属性上,但否定两个匹配的条件更清晰。"$elemMatch": { "weight": { "$ne": "40" }, "size": { "$ne": "40" } }
好歹你
$push
找到一个不符合提供条件的新数组元素。仅在未找到主文档
_id
的情况下尝试“更新插入”,并使用$setOnInsert
因此,如果找到文档,此操作将不执行任何操作。
和以前一样,尽管整个批处理都被发送到服务器,但其中只有一个会实际写入任何内容。
关于mongodb - 在元素不存在的地方插入数组,否则更新它(有多个条件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46806613/