原载于 https://szhshp.org/tech/2019/09/07/mongodbaggregatefunc.html, 转载请注明
需求描述
首先我有一个 Item 的 collection:
type Item {
_id: String
itemname: String!
itemid: String!
itemtype: String!
parent_id: String
}
///
/// 主要是下面这一些部分
type Query {
getItemSummary: ItemSummaryResponse
}
type ItemSummaryResponse {
data: [ItemSummary]
success: Boolean
}
type ItemSummary {
_id: String
count: Int
}
gql 端调用的方法:
{
getItemSummary {
data{
_id
count
}
success
}
}
然按照其中的类别 (itemtype) 进行总计:
那么实际上在后台 mongoose 里面需要这么写:
getItemSummary: root => Item.aggregate([{
$group: {
_id: '$itemtype',
count: {
$sum: 1