您可以使用Aggregation Pipeline 将计算字段添加到结果中。下面有一些使用mongo shell 的示例,但Mongoose 的Aggregate() helper 中的语法类似。
例如,要计算总和(每个用户文档),您可以在 $project stage 中使用 $add expression:
db.user.aggregate(
// Limit to relevant documents and potentially take advantage of an index
{ $match: {
user_id: "foo"
}},
{ $project: {
user_id: 1,
total: { $add: ["$user_totaldocs", "$user_totalthings"] }
}}
)
要计算多个文档的总数,您需要使用 $group stage 和 $sum accumulator,例如:
db.user.aggregate(
{ $group: {
_id: null,
total: { $sum: { $add: ["$user_totaldocs", "$user_totalthings"] } },
totaldocs: { $sum: "$user_totaldocs" },
totalthings: { $sum: "$user_totalthings" }
}}
)
您可能只需要一个 total 字段;我在totaldocs 和totalthings 中添加了计算多个字段的示例。
null 中的_id 组将组合传递到$group 阶段的所有文档中的值,但您也可以在此处使用其他条件(例如按user_id 分组)。