我有一个包含数据的集合
match n where has(n.`longitude`) return n
我按“team.name”进行过滤,想知道状态是什么,并计算每个状态如下样本结果
{ "_id" : "...." , "team" : [ {"name" : "A", "state" : "Active"} , {"name" : "B", "state" : "Deactive", {"name" : "C", "state" : "Unknown"} } ]},
{ "_id" : "...." , "team" : [ {"name" : "A", "state" : "Unknown"} , {"name" : "B", "state" : "Deactive", {"name" : "C", "state" : "Unknown"} } ]},
{ "_id" : "...." , "team" : [ {"name" : "A", "state" : "Active"} , {"name" : "B", "state" : "Deactive", {"name" : "C", "state" : "Unknown"} } ]}
是否可以仅使用MongoDB的聚合函数而不使用任何代码?
答案 0 :(得分:2)
是否可以仅使用MongoDB的聚合函数 码?
是
TL; DR 展开并分组
db.getCollection('foo').aggregate([
{$unwind:"$team"},
{
$group: {
_id: "$team.name",
"Active": {$sum: {$cond:[{$eq:["$team.state","Active"]},1,0]}},
"Deactive": {$sum: {$cond:[{$eq:["$team.state","Deactive"]},1,0]}},
"Unknown": {$sum: {$cond:[{$eq:["$team.state","Unknown"]},1,0]}}
}
},
{$project: {_id:0, name:"$_id", Active:1, Deactive:1, Unknown:1}},
{$sort: {name:1}}
])
样品的输出:
[
{ "name" : "A", "Active" : 2, "Deactive" : 0, "Unknown" : 1 },
{ "name" : "B", "Active" : 0, "Deactive" : 3, "Unknown" : 0 },
{ "name" : "C", "Active" : 0, "Deactive" : 0, "Unknown" : 3 }
]