user50992
user50992

Reputation: 201

MongoDB update nested array

I have a simple structure in mongodb, with nested array. How can I update searched value? I've seen examples using numbers something like this:

invited.0.used: true

but this is not what I'm searching for because I don't know where in my list is this element so how could I update array used to true where key is 84026702? What if I have 100 arrays in invited how to update where key is 43938432?

{
    "_id" : ObjectId("4fed972f61d69aa004000000"),
    "name" : "mezo",
    "invited" : [
            {
                    "key" : 40928710,
                    "used" : false
            },
            {
                    "key" : 84026702,
                    "used" : false
            }
    ]
}

Upvotes: 1

Views: 3801

Answers (1)

Sammaye
Sammaye

Reputation: 43884

update({ invited.key : 84026702 }, { invited.$.used : true });

This basically does what you wanna and should work nicely. Look into positional operators in mongodb: http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator

Or in PHP (as your question is tagged) you can do:

$mongo->collection->update(array('invited.key' => 84026702), array('invited.$.used' => true));

Upvotes: 6

Related Questions