【发布时间】:2019-11-07 12:52:14
【问题描述】:
我的数据库中有学生文档。每个文档都是一个学生,并具有 amountOwed 和 tuition 字段。
我正在尝试更新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?
【问题讨论】:
-
您使用的 mongo 版本是什么? mongo 4.2+ 版本支持 $set(聚合)。
标签: javascript mongodb mongoose mongoose-schema