[英]How to aggregate mongoose collection?
In my mongoose model I have an invoiceHeader and invoiceLine collection both relating to account object. 在我的猫鼬模型中,我有一个与帐户对象有关的invoiceHeader和invoiceLine集合。 In a view I want to display the total invoiceAmount for the account.
在一个视图中,我想显示该帐户的总invoiceAmount。 In SQL something like select sum(amount) from invoiceHeader group by account.
在SQL中,类似按帐户从invoiceHeader组中选择sum(amount)。 How can i achieve similar with nodeJS and mongoose?
如何使用nodeJS和mongoose实现相似的目的?
Assuming amount
is the property that you want to sum on, it would be like: 假设
amount
是您要求和的属性,则如下所示:
InvoiceHeaderModel.aggregate({
$match: {
account: '<Account_ID>'
}
}, {
$group: {
_id: null,
total: {
$sum: "$amount"
}
}
}, {
$project: {
_id: 0,
total: 1
}
}, function(err, res) {
// res contains the result
});
The $match
operator is used to match certain documents. $match
运算符用于匹配某些文档。 The $group
operator is used to group the documents. $group
运算符用于对文档进行分组。 The $project
operator is used to select certain fields from the documents. $project
运算符用于从文档中选择某些字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.