我正在尝试编写一个mongo查询,以帮助从数据生成一个报告。
文档看起来像这样:
[{
"DeviceType" : "A",
"DeviceStatus" : "On"
},
{
"Device Type" : "B",
"Device Status" : "On"
},
{
"DeviceType" : "A",
"DeviceStatus" : "Off"
},
{
"DeviceType" : "A",
"DeviceStatus" : "On"
}]
DeviceType
字段可以采用任何字符串值,DeviceStatus
字段可以是On
、Off
或InRepair
中的任何一个。我想写一个mongo查询,显示每个设备的DeviceStatus
计数。结果应该是这样的:
[{
"DeviceType" : "A",
"DeviceStatusOnCount" : "15",
"DeviceStatusOffCount" : "13",
"DeviceStatusInRepairCount" : "12",
},
{
"DeviceType" : "B",
"DeviceStatusOnCount" : "6",
"DeviceStatusOffCount" : "14",
"DeviceStatusInRepairCount" : "2",
}]
我怎样才能在mongo做到这一点呢?
我当前的查询只能基于DeviceType
进行分组:
db.Collection_Name.aggregate([
{ $group: { _id: "$DeviceType", count: { $sum: 1 } } }
])
1条答案
按热度按时间bwitn5fc1#
您可以使用**$cond**+$eq向**$sum**运算符返回1或0:
测试:mongoplayground