MongoDB update nested array

2020-03-07 06:06发布

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

1条回答
戒情不戒烟
2楼-- · 2020-03-07 06:56
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));
查看更多
登录 后发表回答