MongoDB 2.2-更新数组嵌套文档 [英] MongoDB 2.2 - Updating Array Nested Document

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

问题描述

是否可以使用$ update和$ elemMatch更新Level3数组中的单个文档字段?我意识到在这种情况下我不能多次使用位置运算符,并且由于这些文档不是很大,因此我一直在进行Level2嵌套文档的所需的更深的更改.我希望有一些语法可以使用$ elemMatch更新Level3数组文档,而无需知道目标文档在Level3数组中或在Level2中包含文档的位置.

Is it possible to update a single document field in the Level3 array using $update and $elemMatch? I realize I cannot use the positional operator multiple times given this case and historically I've modified the Level2 nested document with the required deeper changes since these documents aren't very large. I'm hoping there is some syntax that makes it possible to update Level3 array documents using $elemMatch without knowing the position of the target document in the Level3 array or containing document in Level2.

示例:

db.collection.update({_id:'123', level2:{$elemMatch:{'level3.id':'bbb','level3.e1':'hij'}},{'level2.level3.createdDate':new Date()})

{
    _id:'123',
    f1:'abc',
    f2:'def',
    level2:[
        {_
            id:'aaa',
            e1:'hij',
            e2:'lmo'
            level3:[
                {
                    name:'foo',
                    type:'bar',
                    createdDate:'2013-3-28T05:18:00'
                }]
        },
        {_
            id:'bbb',
            e1:'hij',
            e2:'lmo'
            level3:[
                {
                    name:'foo2',
                    type:'bar2',
                    createdDate:'2013-3-28T05:19:00'
                }]
        }
    ]
}

推荐答案

由于您提到的原因,目前无法使用常规更新操作来完成此操作.

There is no way to do this currently using a regular update operation for reasons you noted.

目前唯一可以使用的解决方法是向文档添​​加版本控制,并通过阅读文档,在应用程序中找到要修改的适当元素,更改其值然后使用update来使用乐观锁定.在已读文档中包含该版本(因此,如果其他线程在查询和更新之间更新了该文档,则您不会覆盖所做的更改,而必须重新加载该文档并重试.

The only work around you can use at the moment is to add versioning to your document and use optimistic locking by reading the document, finding the appropriate elements to modify in your application, changing their values and then using an update that includes the version in the read document (so that if other thread updated the document between your query and your update you would not overwrite the changes but would have to reload the document and try again.

版本控制策略不必基于整个文档,您可以对第一级数组元素进行版本控制,然后就可以仅更新所关注的子数组(通过使用$ set进行更新)

The versioning strategy would not have to be based on the entire document, you can version the first level array elements and then you would be able to update just the sub-array you were concerned with (via an update with $set).

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

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