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

查看:68
本文介绍了更新 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?

推荐答案

这里有一个大问题,您是否需要利用 Mongo 的addToSet"和push"操作?如果您真的打算只修改数组中的单个项目,那么您可能应该将这些数组构建为对象.

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.

这是我的结构:

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

这基本上将所有内容转换为 JSON 对象而不是数组.你失去了使用 $push$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': {$exists:true} }, {'$set': {'items.2.blocks.0.txt': 'hi'}})

您还会注意到我已经丢弃了ID".当您嵌套这样的东西时,您通常可以简单地使用该数字作为索引来替换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.

此功能已在 3.6 中添加 表达更新.

This feature has been added in 3.6 with expressive updates.

db.objects.update( {id: 1 }, { $set: { 'items.$[itm].blocks.$[blk].txt': "hi", } }, { multi: false, arrayFilters: [ { 'itm.id': 2 }, { 'blk.id': 3} ] } )

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

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