使用condition更新mongodb上的嵌套元素

问题描述 投票:0回答:2

使用以下集合结构,如何使用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
2个回答
0
投票

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

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

0
投票

可能会有所帮助:

db.collection.update(
 {"sku": "x","prices" : { $elemMatch: { origin : {$nin : ['H','G']} } }}},
 {$set: { "prices.$[].price" : 10}})
© www.soinside.com 2019 - 2024. All rights reserved.