首页 > 解决方案 > Mongodb位置更新所有$ []似乎不起作用

问题描述

我有一个这样的事件集合:

{title: "Some Title", description: "Some Description", products: [{_id: "owkaowakdowakd", quantity: 15}]}

我想在 products 数组的所有元素中添加一个带有空数组的“保留”字段。要得到这个结果:

{title: "Some Title", description: "Some Description", products: [{_id: "owkaowakdowakd", quantity: 15, reserved: [] }]}

查看文档,您可以使用 $[] 运算符对数组的所有元素进行更改。https://docs.mongodb.com/manual/reference/operator/update/positional-all/#positional-update-all

db.events.updateMany( {"products.reserved": {$exists: false}}, {$set: {"products.$[].reserved": []}})

但这会给我一个错误:

2019-12-17T16:03:43.399+0000 E  QUERY    [js] WriteError({
    "index" : 0,
    "code" : 28,
    "errmsg" : "Cannot create field 'reserved' in element {0: null}",
    "op" : {
        "q" : {
            "products.reserved" : {
                "$exists" : false
            }
        },
        "u" : {
            "$set" : {
                "products.$[].reserved" : [ ]
            }
        },
        "multi" : true,
        "upsert" : false
    }
}) :
WriteError({
    "index" : 0,
    "code" : 28,
    "errmsg" : "Cannot create field 'reserved' in element {0: null}",
    "op" : {
        "q" : {
            "products.reserved" : {
                "$exists" : false
            }
        },
        "u" : {
            "$set" : {
                "products.$[].reserved" : [ ]
            }
        },
        "multi" : true,
        "upsert" : false
    }
})

我还尝试修改每个元素的数量,因为这已经存在,但它返回相同的错误!“无法创建字段‘数量’……”

标签: arraysmongodboperator-keyword

解决方案


希望这会有所帮助

添加字段


推荐阅读