You can use the Aggregation Pipeline to add calculated fields to the result. The following are some examples of using the mongo shell, but the syntax in the Mongoose Aggregate () utility is similar.
For example, to calculate the amounts (for each user document), you can use the $add expression in the $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 the totals for several documents, you need to use the $group stage with $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 need only one total field; I have added examples of calculating several fields in totaldocs and totalthings .
The _id of null group will combine the values ββfrom all documents submitted to the $group stage, but you can also use other criteria (for example, group by user_id ).
source share