使用条件更新mongodb上的嵌套元素

时间:2019-04-29 16:47:40

标签: mongodb

使用follow集合结构,如何更新具有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]
        }
    }}
])

2 个答案:

答案 0 :(得分:0)

可能会有所帮助:

db.collection.update(
 {"sku": "x","prices" : { $elemMatch: { origin : {$nin : ['H','G']} } }}},
 {$set: { "prices.$[].price" : 10}})

答案 1 :(得分:0)

您无法使用聚合管道进行更新。因此,Mongodb提供了几种用于更新的方法。尝试以下方法:

db.collection.update(
{$and: [{"sku": "x"}, {"prices.id": 1}, {"prices.origin": {$nin: ["H", "G"]}}]}, 
{$set: {"prices.price": 10}}, {multi:true})
相关问题