更新操作会修改集合中的现有文档。 MongoDB 提供了以下方法来更新集合的文档:

  • [db.collection.updateOne(<filter>, <update>, <options>)](https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/#db.collection.updateOne)
  • [db.collection.updateMany(<filter>, <update>, <options>)](https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/#db.collection.updateMany)
  • [db.collection.replaceOne(<filter>, <update>, <options>)](https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/#db.collection.replaceOne)

您可以指定标识要更新的文档的条件或过滤器。这些过滤器使用与读取操作相同的语法。
更新文档 - 图1

测试数据:

  1. db.inventory.insertMany( [
  2. { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
  3. { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
  4. { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
  5. { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
  6. { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
  7. { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
  8. { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
  9. { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
  10. { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
  11. { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
  12. ] );

语法

为了更新文档,MongoDB 提供了更新操作符(例如 $set)来修改字段值。

要使用更新运算符,请将以下形式的更新文档传递给更新方法:

  1. {
  2. <update operator>: { <field1>: <value1>, ... },
  3. <update operator>: { <field2>: <value2>, ... },
  4. ...
  5. }

如果该字段不存在,则某些更新运算符(例如$ set)将创建该字段。有关详细信息,请参见各个更新操作员参考。

更新单个文档

下面的示例在清单集合上使用 db.collection.updateOne() 方法更新项目等于 paper 的第一个文档:

  1. db.inventory.updateOne(
  2. { item: "paper" },
  3. {
  4. $set: { "size.uom": "cm", status: "P" },
  5. $currentDate: { lastModified: true }
  6. }
  7. )

更新操作:

  • 使用 $set 运算符将 size.uom 字段的值更新为 cm,将状态字段的值更新为 P
  • 使用 $currentDate 运算符将 lastModified 字段的值更新为当前日期。如果 lastModified 字段不存在,则 $currentDate 将创建该字段。

更新多个文档

以下示例在清单集合上使用 db.collection.updateMany() 方法来更新数量小于50的所有文档:

  1. db.inventory.updateMany(
  2. { "qty": { $lt: 50 } },
  3. {
  4. $set: { "size.uom": "in", status: "P" },
  5. $currentDate: { lastModified: true }
  6. }
  7. )

更新操作:

  • 使用 $set 运算符将 size.uom 字段的值更新为 "in",将状态字段的值更新为 "p"
  • 使用 $currentDate 运算符将 lastModified 字段的值更新为当前日期。如果 lastModified 字段不存在,则 $currentDate 将创建该字段。

替换文档

要替换 _id 字段以外的文档的全部内容,请将一个全新的文档作为第二个参数传递给 db.collection.replaceOne()

替换文档时,替换文档必须仅由字段/值对组成;即不包含更新运算符表达式。

替换文档可以具有与原始文档不同的字段。在替换文档中,由于 _id 字段是不可变的,因此可以省略 _id 字段;但是,如果您确实包含 _id 字段,则它必须与当前值具有相同的值。

以下示例替换了清单集合中项目 "paper" 的第一个文档:

  1. db.inventory.replaceOne(
  2. { item: "paper" },
  3. { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
  4. )