MongoDB Update Array element

2019-02-23 23:55发布

问题:

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.