mongodb 如何在mongo中计算多个字段?

x33g5p2x  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(201)

我正在尝试编写一个mongo查询,以帮助从数据生成一个报告。
文档看起来像这样:

[{
    "DeviceType" : "A",
    "DeviceStatus" : "On"
},
{
    "Device Type" : "B",
    "Device Status" : "On"
},
{
    "DeviceType" : "A",
    "DeviceStatus" : "Off"
},
{
    "DeviceType" : "A",
    "DeviceStatus" : "On"
}]

DeviceType字段可以采用任何字符串值,DeviceStatus字段可以是OnOffInRepair中的任何一个。我想写一个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 } } }
])
bwitn5fc

bwitn5fc1#

您可以使用**$cond**+$eq向**$sum**运算符返回1或0:

db.collection.aggregate([
  {
    $group: {
      _id: "$DeviceType",
      DeviceStatusOnCount: { $sum: { $cond: [ { $eq: [ "$DeviceStatus", "On" ] }, 1, 0 ] } },
      DeviceStatusOffCount: { $sum: { $cond: [ { $eq: [ "$DeviceStatus", "Off" ] }, 1, 0 ] } },
      DeviceStatusInRepairCount: { $sum: { $cond: [ { $eq: [ "$DeviceStatus", "InRepair" ] }, 1, 0 ] } }
    }
  },
  {$addFields: {DeviceType: '$_id'}}, {$project: {_id:0}}
])

测试:mongoplayground

相关问题