使用以下集合结构,如何使用if
条件更新列表中对象的特定键?
“如果关键'起源'不是'H'或'G',则更新关键'价格'”
{
"sku": "x",
"prices": [
{
"id": "0",
"price": 234.56,
"origin": "H"
},
{
"id": "1",
"price": 345.67,
"origin": "J"
}
]
}
我尝试使用$cond
与$set
,但我得到错误:Unrecognized pipeline stage name: '$set'
,这是一个例子:
https://mongoplayground.net/p/o1SAirsmRvf
db.collection.aggregate([
{$match: {sku: 'x', 'prices.id': '1'}},
{$set: {
'prices.$.price': {
$cond: [{
$or: [
{$ne: ['prices.$.origin', 'H']},
{$ne: ['prices.$.origin', 'G']},
]
}, 10, 20]
}
}}
])
您无法使用聚合管道进行更新。因此,Mongodb提供了几种用于更新的方法。试试以下内容:
db.collection.update(
{$and: [{"sku": "x"}, {"prices.id": 1}, {"prices.origin": {$nin: ["H", "G"]}}]},
{$set: {"prices.price": 10}}, {multi:true})
可能会有所帮助:
db.collection.update(
{"sku": "x","prices" : { $elemMatch: { origin : {$nin : ['H','G']} } }}},
{$set: { "prices.$[].price" : 10}})