可以使用Aggregation Pipeline来计算字段添加到结果。下面有一些使用mongo
shell的例子,但Mongoose的Aggregate() helper中的语法是相似的。
例如,要计算总和(每用户文件),你可以在使用$add
expression一个$project
stage:
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
如分组)使用其他标准。