【问题标题】:Update multiple array elements with $inc使用 $inc 更新多个数组元素
【发布时间】:2020-09-23 13:00:48
【问题描述】:

我有以下文件

{store : {
        id        : 'STORE1',
        name      : 'Electronics Store',
        locations : [
            {
                id       : 'LOC1',
                quantity : 4
            },
            {
                id       : 'LOC2',
                quantity : 10
            },
            {
                id       : 'LOC3',
                quantity : 5
            }
        ]
    }
}

我想根据 id 字段使用 $inc 更新 locations 数组的多个元素的 quantity

例如,我想用 +5 更新 id : 'LOC1'quantity 字段,并用 +2 更新 id : LOC3 到它的 quantity 字段。

是否可以在 mongodb 中使用一个查询而不是对每个位置使用多个查询。

【问题讨论】:

标签: mongodb mongodb-query


【解决方案1】:

您可以使用filtered positional operator $[<identifier>]。下面的代码会有所帮助:

db.collection.update(
     {},
     {$inc: {'store.locations.$[elem1].quantity': 5, 'store.locations.$[elem2].quantity': 2}},
     {arrayFilters: [{'elem1.id': 'LOC1'}, {'elem2.id': 'LOC3'}]}
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多