【问题标题】:MongoDB: Updating a document with existing fields using aggregationMongoDB:使用聚合更新包含现有字段的文档
【发布时间】:2021-10-31 18:07:06
【问题描述】:

我是 mongodb 的新手,我正在学习一些 Udemy 课程,我想知道如何更新文档现有字段而不覆盖它。

我有以下这些文件的集合:

enter image description here

我想在stock 字段的"item":"drafts" 中添加新的warehouses

我正在尝试的是:

enter image description here

并且给出的输出似乎有效,但是当我再次db.matrices.find() 时,我得到的是与第一张图片中完全相同的输出。

如何更新它?我也尝试过update 方法,但没有做我想做的事。

谢谢!

PD:我正在使用 linux mint、mongo v5.0.3 和 mongosh v1.1.1

【问题讨论】:

  • 如果您可以在 text 而不是 images 中提供示例数据和预期数据,将会很有帮助

标签: mongodb nosql


【解决方案1】:

您正在使用aggregate 管道,这不会更新数据库中的文档,它只是检索结果。从 Mongo 4.2+ 版开始,您现在可以使用聚合管道(有一些限制)到update a document,如下所示:

db.collection.updateOne({
  item: "drafts"
},
[
  {
    $set: {
      stock: {
        $concatArrays: [
          "$stock",
          [
            {
              "warehouse": "A",
              qty: 20
            }
          ]
        ]
      }
    }
  }
])

Mongo Playground

我只会说这个特定的更新非常简单,不需要使用聚合管道。在更新字段中简单地使用$push 操作符就足以进行“正常”更新:

db.collection.updateOne({
  item: "drafts"
},
{
  $push: {
    stock: {
      "warehouse": "A",
      qty: 20
    }
  }
})

Mongo Playground

【讨论】:

  • 好的!非常感谢你!我在发布之前在网上搜索,但总是弹出没有 $push 运算符的“更新”选项!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 2015-01-04
  • 2022-12-02
  • 2023-02-11
相关资源
最近更新 更多