You can use the Aggregation Pipeline to add calculated fields to a result. There are some examples below using the mongo
shell, but the syntax in Mongoose's Aggregate() helper is similar.
For example, to calculate sums (per user document) you can use the $add
expression in a $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"] }
}}
)
To calculate totals across multiple documents you need to use a $group
stage with a $sum
accumulator, for example:
db.user.aggregate(
{ $group: {
_id: null,
total: { $sum: { $add: ["$user_totaldocs", "$user_totalthings"] } },
totaldocs: { $sum: "$user_totaldocs" },
totalthings: { $sum: "$user_totalthings" }
}}
)
You may want only the one total
field; I've added in totaldocs
and totalthings
as examples of calculating multiple fields.
A group _id
of null
will combine values from all documents passed to the $group
stage, but you can also use other criteria here (such as grouping by user_id
).