MongoDB更新嵌套数组 [英] MongoDB update nested array

查看:79
本文介绍了MongoDB更新嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongodb中有一个简单的结构,带有嵌套数组。如何更新搜索值?
我见过类似这样的数字的例子:

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

但这不是我要搜索的内容,因为我不知道我的列表中的这个元素在哪里所以如何如果密钥是84026702,我可以更新用于true的数组吗?如果我有100个阵列被邀请如何更新密钥是43938432怎么办?

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


推荐答案

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

这基本上是你想要的,应该很好地工作。查看mongodb中的位置运算符: http://www.mongodb.org/display/DOCS/Updating #更新 - %24positionaloperator

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

或者在PHP中(如你的问题被标记)你可以这样做:

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

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

这篇关于MongoDB更新嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆