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

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

问题描述

我最近开始使用 MongoDB,我有一个关于更新文档中的数组的问题.我有这样的结构:

<代码>{"_id" : ObjectId(),邮政" : "",注释" : [{用户":测试","头像": "/static/avatars/asd.jpg",文本" : "....."}{用户":测试","头像": "/static/avatars/asd.jpg",文本" : "....."}{用户":测试","头像": "/static/avatars/asd.jpg",文本" : "....."}...]}

我正在尝试执行以下查询:

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

问题在于它更新了所有文档,但它只更新了每个文档中的第一个数组元素.有没有办法更新所有数组元素,或者我应该尝试手动完成?谢谢.

解决方案

不能在单个更新操作中修改多个数组元素.因此,您必须重复更新才能迁移需要修改多个数组元素的文档.您可以通过遍历集合中的每个文档来实现此目的,使用 $elemMatch 重复应用更新,直到文档的所有相关注释都被替换,例如:

<前>db.collection.find().forEach(function(doc) {做 {db.collection.update({_id: doc._id,评论:{$elemMatch:{用户:测试",头像:{$ne:"new_avatar.jpg"}}}},{$set:{"comments.$.avatar":"new_avatar.jpg"}});} while (db.getPrevError().n != 0);})

请注意,如果您的应用程序要求此操作的效率,您应该规范化您的架构,以便用户头像的位置存储在单个文档中,而不是每个评论中.

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.

解决方案

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天全站免登陆