MongoDB Update Array element

安稳与你 提交于 2019-12-04 03:58:53

问题


I have a document structure like

{
    "_id" : ObjectId("52263922f5ebf05115bf550e"),
    "Fields" : [
        {
            "Field" : "Lot No",
            "Rules" : [ ]
        },
        {
            "Field" : "RMA No",
            "Rules" : [ ]
        }
    ]
}

I have tried to update by using the following code to push into the Rules Array which will hold objects.

db.test.update({
    "Fields.Field":{$in:["Lot No"]}
}, {
    $addToSet: {
        "Fields.Field.$.Rules": {
            "item_name": "my_item_two",
            "price": 1
        }
    }
}, false, true);

But I get the following error:

can't append to array using string field name [Field]

How do I do the update?


回答1:


You gone too deep with that wildcard $. You match for an item in the Fields array, so you get a access on that, with: Fields.$. This expression returns the first match in your Fields array, so you reach its fields by Fields.$.Field or Fields.$.Result.

Now, lets update the update:

db.test.update({
    "Fields.Field": "Lot No"
}, {
    $addToSet: {
        "Fields.$.Rules": {
            'item_name': "my_item_two",
            'price':1
        }
    }
}, false, true);

Please note that I've shortened the query as it is equal to your expression.



来源:https://stackoverflow.com/questions/18600791/mongodb-update-array-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!