【问题标题】:How to update objects in array in Mongo如何在 Mongo 中更新数组中的对象
【发布时间】:2020-08-13 17:34:41
【问题描述】:

我非常擅长 SQL,但即使是最简单的 Mongo 查询我也很吃力。

post 集合中的我的文档如下所示(简化)

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

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

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

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

【问题讨论】:

标签: mongodb updates


【解决方案1】:

我想你在找FindAndModify

db.runCommand({
  findAndModify: "post",
  query: { user_id: 123 },
  update: { $set: { user_id: 'abc' } }
})

编辑

如果multi 设置为true,我相信您可以使用update 对集合执行类似的操作:

db.post.update(
  { user_id: 123 },
  { $set: { user_id: 'abc' } },
  { multi: true }
)

【讨论】:

  • 我需要修改所有个文档,而不仅仅是一个。我更新了我的问题,使其更加明确。
【解决方案2】:

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

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

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

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

假设您的文档结构如下:

{
    "_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 查询来执行此操作。 相反,我将遍历文档并按如下方式执行。

// 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 将如下所示:

{
    "_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 将如下所示:

{
    "_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"}]
}

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

【讨论】:

    【解决方案3】:

    您可以使用 v3.6 中的arrayFilters

    db.post.updateMany(
      { 'comments.user_id': '123' },
      { 
        $set: {
          'comments.$[elem].user_id': 'abc' 
        }
      },
      { 
        arrayFilters: [
          { 'elem.user_id': '123' }
        ]
      }
    );
    

    【讨论】:

      猜你喜欢
      • 2015-12-20
      • 2019-11-23
      • 1970-01-01
      • 2023-04-07
      • 2015-05-05
      • 2018-10-15
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多