I'm trying to write a Mongoose aggregation query to get the sum of a field for all matching documents.
Meaning I have a model that looks like:
{
itemNumber: String,
quantity: Number
}
There are multiple documents with the same itemNumber, I'm looking to get the sum of the quantity fields.
What's the easiest way to do this?
CodePudding user response:
use group
db.collection.aggregate([
{
$group: {
_id: "$itemNumber",
count: {
$sum: "$quantity"
}
}
}
])