MongoDB:使用聚合更新包含现有字段的文档

MongoDB: Updating a document with existing fields using aggregation

我是 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

您正在使用 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