可能以下示例对您有用。
假设您有以下样本数据。
db.sample.insert([
{
"_id" : 27001,
"assigned_to" : "abc@xyz.com",
"priority" : "High"
}
,{
"_id" : 27002,
"assigned_to" : "jkdj@xyz.com",
"priority" : "Low"
},
{
"_id" : 27003,
"assigned_to" : "abc@xyz.com",
"priority" : "High"
}
]);使用下面的聚合查询来获取
1.总数
2.Count where assigend_to是“abc@xyz.com”
3.Count优先级为“高”
db.sample.aggregate({$group:{
_id: 0,total:{$sum:1},
'assigned_to' : { $sum : { $cond: [ { $eq: [ '$assigned_to' , 'abc@xyz.com' ] }, 1, 0 ] } },
'hight_priority' : { $sum : { $cond: [ { $eq: [ '$priority' , 'High' ] }, 1, 0 ] } }
}
}
);你会得到预期的结果
{
"result" : [
{
"_id" : 0,
"total" : 3,
"assigned_to" : 2,
"hight_priority" : 2
}
],
"ok" : 1
}