更新在MongoDB中嵌套数组 [英] Updating nested arrays in mongodb

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

问题描述

我在MongoDB中与我需要更新的对象2级深度嵌套数组的文件,是这样的:

I have a document in mongodb with 2 level deep nested array of objects that I need to update, something like this:

{
    id: 1,
    items: [
        {
            id: 2,
            blocks: [
                {
                    id: 3
                    txt: 'hello'
                }
            ]
        }
    ] 
}

如果有只有一个级别深阵列我可以使用位置运营商,但对于第二个层面,我想出了唯一的选择更新对象是使用位置运营商使用嵌套对象的指数,像这样的:

If there was only one level deep array I could use positional operator to update objects in it but for second level the only option I've came up is to use positional operator with nested object's index, like this:

db.objects.update({'items.id': 2}, {'$set': {'items.$.blocks.0.txt': 'hi'}})

这方法有效,但它似乎危险的我,因为我建立一个Web服务,索引号应该是来自客户端,它可以发送100000说为指标,这将迫使MongoDB的创建100000索引和空值的数组。

This approach works but it seems dangerous to me since I'm building a web service and index number should come from client which can send say 100000 as index and this will force mongodb to create an array with 100000 indexes with null value.

是否有任何其他的方式来更新这些嵌套的对象,我可以参考对象的ID,而不是它的位置或者方法来检查,如果提供的索引超出范围在查询中使用它之前?

Are there any other ways to update such nested objects where I can refer to object's ID instead of it's position or maybe ways to check if supplied index is out of bounds before using it in query?

推荐答案

下面是一个大问题,你需要利用蒙戈的addToSet和推的操作?如果你真的打算在阵列中只修改单个项目,那么你或许应该建立这些数组作为对象。

Here's the big question, do you need to leverage Mongo's "addToSet" and "push" operations? If you really plan to modify just individual items in the array, then you should probably build these arrays as objects.

下面是我会怎么构建这样的:

Here's how I would structure this:

{
    id: 1,
    items: 
        { 
          "2" : { "blocks" : { "3" : { txt : 'hello' } } },
          "5" : { "blocks" : { "1" : { txt : 'foo'}, "2" : { txt : 'bar'} } }
        }
}

这基本上都转换到JSON对象而不是数组。你失去了使用 $推 $ addToSet 但我认为这让一切更容易的能力。例如,您的查询应该是这样的:

This basically transforms everything in to JSON objects instead of arrays. You lose the ability to use $push and $addToSet but I think this makes everything easier. For example, your query would look like this:

db.objects.update({'items.2:{$存在:真}},{'$集:{items.2.blocks.0.txt':'喜'}})

您还会注意到我甩了标识。当你嵌套这样的事情,你可以用通常简单地使用该号码作为索引代替ID。在ID的概念现在是隐含的。

You'll also notice that I've dumped the "IDs". When you're nesting things like this you can generally replace "ID" with simply using that number as an index. The "ID" concept is now implied.

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

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