user11909
user11909

Reputation: 1265

Update a object field in an array

In mondodb I want to update a field of an object within an array. The example database looks like this:

{
    "_id" : ObjectId("5ad237559d30d918c89c7f46"),
    "myArray" : [
        {
            "name" : "a",
            "name2" : "a",
            "value" : 900000 //<--- instead of this...
        },
        {
            "name" : "b",
            "name2" : "b",
            "value" : 0
        }
    ]
},
{
    "_id" : ObjectId("5ad238049d30d918c89c7f47"),
    "myArray" : [
        {
            "name" : "b",
            "name2" : "b",
            "value" : 0
        },
        {
            "name" : "c",
            "name2" : "a",
            "value" : 0 //... I want to update this
        }
    ]
}

I want to update the last value field by querying name:c AND name2:a. I tried it with the following instruction, but it sets the value of the first object (name:a name2:a). Does the problem lie near the $ char?

db.test.updateOne({$and:[{"myArray.name" : "c"}, {"myArray.name2" : "a"}]},
                 {$set:{"myArray.$.value" : 900000}})

Upvotes: 0

Views: 48

Answers (2)

ProgrammingLlama
ProgrammingLlama

Reputation: 38850

You need to do an $elemMatch to match the specific item in the array and then you can use the positional operator:

db.test.updateOne(
    { "myArray": { $elemMatch: { "name": "c", "name2"; "a" } } },
    { $set: { "myArray.$.value": 900000 } }
);

Upvotes: 1

Julien TASSIN
Julien TASSIN

Reputation: 5212

You can use arrayFilters.

db.test.updateOne({}, {$set:{"myArray.$[element].value" : 900000}}   { 
 multi: true,
 arrayFilters: [ {$and:[{"element.name" : "c"}, {"element.name2" : "a"}]}        ]
}, 
)

Sorry, I have no mongodb right there to test it, the query will probably need to be tuned a little

Upvotes: 1

Related Questions