I have a BlogPost
model, and two of its attributes are draft: Boolean
and user: String
.
我有一个BlogPost模型,它的两个属性是draft:Boolean和user:String。
Is it possible to get the following counts in one query using mongo's aggregation framework with Mongoose?
是否可以使用mongo的聚合框架与Mongoose在一个查询中获得以下计数?
BlogPost.count({ user: userID }, function(err, response() {});
BlogPost.count({ user: userID, draft: true }, function(err, response() {});
1 个解决方案
#1
3
The $cond
operator is a ternary operator that evaluates a conditional expression to true/false
and returns either the second or third arguments respectively depending on the evaluation. Your field in this case is either boolean true/false
, so there is no need to test with another operator. You implement this inside the $sum
:
$ cond运算符是一个三元运算符,它将条件表达式求值为true / false,并根据求值分别返回第二个或第三个参数。在这种情况下,您的字段是布尔值true / false,因此无需使用其他运算符进行测试。你在$ sum中实现了这个:
BlogPost.aggregate(
[
{ "$group": {
"_id": null,
"total_count": { "$sum": 1 },
"draft_count": { "$sum": { "$cond": [ "$draft", 1, 0 ] } }
}
],
function(err,results) {
}
);
Passing in null
to the _id
value of group means that you are not "grouping" on any specific document key but are grouping all of the documents in the collection.
将null传递给group的_id值意味着您不是对任何特定文档键进行“分组”,而是将所有文档分组。
#1
3
The $cond
operator is a ternary operator that evaluates a conditional expression to true/false
and returns either the second or third arguments respectively depending on the evaluation. Your field in this case is either boolean true/false
, so there is no need to test with another operator. You implement this inside the $sum
:
$ cond运算符是一个三元运算符,它将条件表达式求值为true / false,并根据求值分别返回第二个或第三个参数。在这种情况下,您的字段是布尔值true / false,因此无需使用其他运算符进行测试。你在$ sum中实现了这个:
BlogPost.aggregate(
[
{ "$group": {
"_id": null,
"total_count": { "$sum": 1 },
"draft_count": { "$sum": { "$cond": [ "$draft", 1, 0 ] } }
}
],
function(err,results) {
}
);
Passing in null
to the _id
value of group means that you are not "grouping" on any specific document key but are grouping all of the documents in the collection.
将null传递给group的_id值意味着您不是对任何特定文档键进行“分组”,而是将所有文档分组。