0

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}})

2 Answers 2

1

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 } }
);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.