MongoDB Update Array element

2019-02-23 23:35发布

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条回答
再贱就再见
2楼-- · 2019-02-24 00:20

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.

查看更多
登录 后发表回答