我正在尝试运行mongo查询以按状态对所有记录进行分组。然后我想得到每个状态的计数。我已设法使用$group
查询执行此操作,但现在我想更进一步,使属性名称反映状态,值等于计数。有没有办法可以做到这一点?
编辑:这与标记为重复的问题不同 我仍然需要按状态分组,我不能按状态分组并在同一组中获得状态总和。重复的问题是按名称分组并根据标题获取日志总和,标题是嵌入文档的总和,而不是所有文档的总和。状态未嵌入它是每个文档的单一属性。
Mongo查询:
db.getCollection('winapplications').aggregate([
{ $match: { 'WINNbr': { '$exists': true, '$ne': '' } } },
{ $match: {"Status":{"$ne":"Approved"}}},
{ $match: {"Status":{"$ne":""}}},
{ $match: {"Status":{"$ne":null}}},
{
$group: {
_id: "$Status",
count:{$sum:1}
}
}
])
结果:
{
"_id" : "Hold",
"count" : 1.0
}
{
"_id" : "Pending",
"count" : 235.0
}
{
"_id" : "Not Approved",
"count" : 4199.0
}
{
"_id" : "Active",
"count" : 1923.0
}
{
"_id" : "Closed",
"count" : 20189.0
}
我想要的是什么:
{
"Hold" : 1
"Pending" : 235
"Not Approved" : 4199
"Active" : 1923
"Closed" : 20189,
}
当我做重复问题时所得的结果不是我要求的结果:
/* 1 */
{
"_id" : "Hold",
"Active" : 0.0,
"Closed" : 0.0,
"Pending" : 0.0,
"Hold" : 1.0,
"Not Approved" : 0.0
}
/* 2 */
{
"_id" : "Pending",
"Active" : 0.0,
"Closed" : 0.0,
"Pending" : 235.0,
"Hold" : 0.0,
"Not Approved" : 0.0
}
/* 3 */
{
"_id" : "Not Approved",
"Active" : 0.0,
"Closed" : 0.0,
"Pending" : 0.0,
"Hold" : 0.0,
"Not Approved" : 4199.0
}
/* 4 */
{
"_id" : "Active",
"Active" : 1923.0,
"Closed" : 0.0,
"Pending" : 0.0,
"Hold" : 0.0,
"Not Approved" : 0.0
}
/* 5 */
{
"_id" : "Closed",
"Active" : 0.0,
"Closed" : 20189.0,
"Pending" : 0.0,
"Hold" : 0.0,
"Not Approved" : 0.0
}