Čamo
Čamo

Reputation: 4182

Mongodb how to update more than one array documents

Can somebody tell me please how to update more than one element in array? I have object like:

{
    _id: 1,
    name: 'x',
    someArray: [
        {'a': 1},
        {'a': 1, 'b': 2},
        {'a': 2}
    ]
}

I would like to update all elements in someArray where 'a' == 1. I tried to do it via command

db.collection.update(
    {_id: 1, 'somaArray.a': 1}, 
    {$set: {'someArray.$.c': 3}}, 
    {multi: true}
)

but this command updated only one element in someArray. The second one is not updated. Result seems like:

{
    _id: 1,
    name: 'x',
    someArray: [
        {'a': 1, 'c': 3},
        {'a': 1, 'b': 2},
        {'a': 2}
    ]
}

How to achieve update of all elements which match the condition? Thank you.

Upvotes: 1

Views: 71

Answers (2)

Rakan Ajlouni
Rakan Ajlouni

Reputation: 16

i think this question is similar to yours

visit (How to Update Multiple Array Elements in mongodb)! and check it out

Upvotes: 0

Jitendra
Jitendra

Reputation: 3185

Try as below: (Read)

db.collection.update({_id:1},
    {
        $set: {
            'someArray.$[elem].c': 3 
        }        
    },
    { arrayFilters: [{ "elem.a": 1 }], multi: true, "upsert": true }
)

Result response will be as below:

{
    "_id" : 1,
    "name" : "x",
    "someArray" : [
        {
            "a" : 1,
            "c" : 3
        },
        {
            "a" : 1,
            "b" : 2,
            "c" : 3
        },
        {
            "a" : 2
        }
    ]
}

Upvotes: 1

Related Questions