如何在 Mongo 中更新数组中的对象 [英] How to update objects in array in Mongo

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

问题描述

我非常擅长 SQL,但即使是最简单的 Mongo 查询,我也很挣扎.

I'm quite good at SQL, but I'm struggling with even the simplest Mongo queries.

我在 post 集合中的文档看起来像这样(简化)

My documents in the post collection looks like this (simplified)

{
     '_id': 5
     'body': 'Correct horse battery staple',
     'comments': 
     [{
          user_id: '123'
      }, 
      {
          user_id: '456'
      }, 
      {
          user_id: '123'
      }]
}

我需要将所有帖子的 '123'user_id's 更新为 'abc'.

I need to update the user_id's that are '123' to 'abc' for all posts.

在 SQL 数据库中,我会有一个 post 表和一个 comment 表,然后执行以下操作:

In a SQL database, I would have a post table and a comment table and do this:

UPDATE comment SET user_id = 'abc' WHERE user_id = '123'

推荐答案

默认情况下,mongodb update 命令只会更新一个文档.

By default, mongodb update command will update only one document.

db.collection.update({document to be found},{changes to be done})

要更新多个文档,您应该包含 multi 关键字.

To update multiple document, you should include multi keyword.

db.collection.update({document to be found},{changes to be done},{multi:true})

假设您的文档结构如下:

Assuming your document structure as below:

{
    "_id": 5,
    "body": "Correct horse battery staple",
    "comments": [{"user_id": "123"},{"user_id": "456"},{"user_id": "123"}]
}
{
    "_id": 6,
    "body": "Correct horse battery staple",
    "comments": [{"user_id': "23"},{"user_id": "123"},{"user_id": "13"}]
}

在这种情况下,我可能需要更新数组中的多个元素以及多个文档.没有默认的 mongodb 查询可以做到这一点.相反,我将遍历文档并按如下方式进行.

In this case, i may need to update multiple elements inside an array as well as multiple documents. There is no default mongodb query to do it. Instead i will loop through documents and do it as follows.

// loop until all documents has been updated
while(db.post.find({'comments.user_id':'123'}).count()!=0) 
{
    db.post.update(
                     { 'comments.user_id':'123' },
                     { $set:{'comments.$.user_id':'abc'} },
                     { multi:true }
                   )
}

在第一次循环运行后,post collection 将如下所示:

After the 1st loop run, post collection will look like:

{
    "_id": 5,
    "body": "Correct horse battery staple",
    "comments": [{"user_id": "abc"},{"user_id": "456"},{"user_id": "123"}]
}
{
    "_id": 6,
    "body": "Correct horse battery staple",
    "comments": [{"user_id": "23"},{"user_id": "abc"},{"user_id": "13"}]
}

在第二次循环运行后,post collection 将如下所示:

After the 2nd loop run, post collection will look like:

{
    "_id": 5,
    "body": "Correct horse battery staple",
    "comments": [{"user_id": "abc"},{"user_id": "456"},{"user_id": "abc"}]
}
{
    "_id": 6,
    "body": "Correct horse battery staple",
    "comments": [{"user_id": "23"},{"user_id": "abc"},{"user_id": "13"}]
}

在第三次循环运行中,循环终止.

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

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