我在worksheets
集合中有数据,如下所示:
/* 1 */
{
"_id" : ObjectId("5c21d780f82aa31334ab6506"),
"isBilling" : true,
"hours" : 6,
"userId" : ObjectId("5c1f38a1d7537d1444738467"),
"projectId": ObjectId("5c1f38a1d7537d1444731234");
}
/* 2 */
{
"_id" : ObjectId("5c21d780f82aa31334ab6507"),
"isBilling" : true,
"hours" : 4,
"userId" : ObjectId("5c1f38a1d7537d1444738493"),
"projectId": ObjectId("5c1f38a1d7537d1444734567");
}
/* 3 */
{
"_id" : ObjectId("5c21e10fae07cc1204a5b647"),
"isBilling" : false,
"hours" : 8,
"userId" : ObjectId("5c1f388fd7537d1444738492"),
"projectId": ObjectId("5c1f38a1d7537d1444731234");
}
我正在使用以下汇总查询来获取字段总数:
Worksheet.aggregate([
{
$match: conditions
},
{
"$group": {
"_id": null,
"billingHours": {
"$sum": {
"$cond": [{ "$eq": ["$isBilling", true] }, "$hours", 0]
}
},
"fixContract": {
"$sum": {
"$cond": [{ "$eq": ["$isBilling", true] }, 0, "$hours"]
}
}
}
}
])
现在,我想要唯一的projectId
字段的总和。上面是 2 。我通过在上面实现的查询中应用两个$ group来尝试它。但这是行不通的。我想得到如下结果:
[
{
"_id": null,
"billingHours": 0,
"fixContract": 8,
"totalProjects": 2
}
]
答案 0 :(得分:1)
使用$addToSet
累加器,然后使用$size
运算符来计算唯一projectId
的数量
Worksheet.aggregate([
{ $match: conditions },
{ "$group": {
"_id": null,
"billingHours": {
"$sum": {
"$cond": [{ "$eq": ["$isBilling", true] }, "$hours", 0]
}
},
"fixContract": {
"$sum": {
"$cond": [{ "$eq": ["$isBilling", true] }, 0, "$hours"]
}
},
"projectIds": { "$addToSet": "$projectId" }
}},
{ "$addFields": { "projectIds": { "$size": "$projectIds" }}}
])