阵列的MongoDB的更新多条记录 [英] MongoDB update multiple records of array

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

问题描述

我最近开始使用MongoDB的,我有一个关于文件中更新阵列的问题。
我得到的结构是这样的:

I recently started using MongoDB and I have a question regarding updating arrays in a document. I got structure like this:

{
"_id" : ObjectId(),
"post" : "",
"comments" : [
        {
                "user" : "test",
                "avatar" : "/static/avatars/asd.jpg",
                "text" : "....."
        }
        {
                "user" : "test",
                "avatar" : "/static/avatars/asd.jpg",
                "text" : "....."
        }
        {
                "user" : "test",
                "avatar" : "/static/avatars/asd.jpg",
                "text" : "....."
        }
        ...
   ]
}

我想请执行以下查询:

I'm trying to execute the following query:

update({"comments.user":"test"},{$set:{"comments.$.avatar": "new_avatar.jpg"}},false,true)

的问题是,它更新的所有文件,但它仅更新每个文档中的第一个数组元素。有什么办法更新所有的数组元素或者我应该尝试做手工?
谢谢你。

The problem is that it update all documents, but it update only the first array element in every document. Is there any way to update all array elements or I should try to do it manually? Thanks.

推荐答案

您不能修改在一个单一的更新操作多个数组元素。因此,你必须重复更新以便迁移这就需要多个数组元素进行修改的文档。你可以通过每个文档集合中迭代,重复应用的更新与 $ elemMatch 直到文档其所有相关评论所取代,例如这样做:

You cannot modify multiple array elements in a single update operation. Thus, you'll have to repeat the update in order to migrate documents which need multiple array elements to be modified. You can do this by iterating through each document in the collection, repeatedly applying an update with $elemMatch until the document has all of its relevant comments replaced, e.g.:


db.collection.find().forEach( function(doc) {
  do {
    db.collection.update({_id: doc._id,
                          comments:{$elemMatch:{user:"test",
                                                avatar:{$ne:"new_avatar.jpg"}}}},
                         {$set:{"comments.$.avatar":"new_avatar.jpg"}});
  } while (db.getPrevError().n != 0);
})

请注意,如果这个操作的效率是您的应用程序的要求,你应该正常化您的架构使得用户的头像的位置存储在一个文档中,而不是在每一个评论。

Note that if efficiency of this operation is a requirement for your application, you should normalize your schema such that the location of the user's avatar is stored in a single document, rather than in every comment.

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

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