sakirow
sakirow

Reputation: 229

How to find and update nested array element in an object on mongodb

I have a collection down below. I am trying to update an array element.

I am trying to update if lineItem _id value is 1 then go to spec list and update characteristicsValue from 900 to 50 if specName is "Model", as you can see, _id is also an array.

collection data:

    {
    "_id": "100",
    "name": "Campaign",
    "status": "Active",
    "parts": {
        "lineItem": [
            {
                "_id": [
                    {
                        "name": "A",
                        "value": "1"
                    }
                ],
                "spec": [
                    {
                        "specName": "Brand",
                        "characteristicsValue": [
                            {
                                "value": "500"
                            }
                        ]
                    },
                    {
                        "specName": "Model",
                        "characteristicsValue": [
                            {
                                "value": "900"
                            }
                        ]
                    }
                ]
            },
            {
                "_id": [
                    {
                        "name": "B",
                        "value": "2"
                    }
                ],
                "spec": [
                    {
                        "specName": "Brand",
                        "characteristicsValue": [
                            {
                                "value": "300"
                            }
                        ]
                    },
                    {
                        "specName": "Model",
                        "characteristicsValue": [
                            {
                                "value": "150"
                            }
                        ]
                    }
                ]
            },
            {
                "_id": [
                    {
                        "name": "C",
                        "value": "2"
                    }
                ]
            }
        ]
    }
}

related update doesnt work as I expected.

 db.Collection.update({"parts.lineItem._id.value" : "1", 
    "parts.lineItem.spec.specName" : "Model"  },{ $set: { 
    "parts.lineItem.spec.$.characteristicsValue" : "50" } })

EDIT: Every _id has a spec array. so, we need to find _id and then go to spec under _id array, find the brand and update the value.

Upvotes: 0

Views: 1052

Answers (1)

Haruo
Haruo

Reputation: 516

Try this way:

db.Collection.update(
   {},
{ $set: { "parts.lineItem.$[outer].spec.$[inner].characteristicsValue" : "50" } },
{ multi: true, arrayFilters: [{"outer._id.value" : "1"}, {"inner.specName" : "Model"}]}
);

Upvotes: 1

Related Questions