【问题标题】:Update all a field in all document based on another field in that document根据该文档中的另一个字段更新所有文档中的所有字段
【发布时间】:2019-11-07 12:52:14
【问题描述】:

我的数据库中有学生文档。每个文档都是一个学生,并具有 amountOwedtuition 字段。

我正在尝试更新amountOwed 等于amountOwed + tuition. 的当前值

我考虑过使用 .find 查询来获取所有学生文档,遍历每个文档并更新数据库。

我还研究并在 mongo 文档中找到了 $set(aggregation)$addFields(aggregation),但我不确定是否可以将其用于我的目的正在努力。

示例文档:

{"studentName" : "Student1",

 "amountOwed" : 100,

 "tuition" : 100

},

{"studentName" : "Student2",

 "amountOwed" : 0,

 "tuition" : 500

}

输出应该是:

{"studentName" : "Student1",

 "amountOwed" : 200,

 "tuition" : 100

},

{"studentName" : "Student2",

 "amountOwed" : 500,

 "tuition" : 500

}

有没有办法在一个数据库查询中完成所有这些操作?

也许使用updateMany

【问题讨论】:

标签: javascript mongodb mongoose mongoose-schema


【解决方案1】:

要添加值,您可以使用 Mongo 聚合查询的 $add 表达式。

尝试使用查询:

db.collection.aggregate([
  {
    $project: {
      studentName: 1,
      tuition: 1,
      _id: 0,
      amountOwed: {
        $add: [
          "$amountOwed",
          "$tuition"
        ]
      }
    }
  }
])

【讨论】:

  • 他不想查询集合,他想更新所有文档。请阅读问题。
  • 所以只需在聚合查询的末尾添加一个 {$out :"collection"} 阶段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 2019-07-15
相关资源
最近更新 更多