如何按多个键和值进行分组

时间:2017-05-21 07:49:27

标签: mongodb

我有一组文档,其中每个文档都有一个带有两个值的nestes字段outside

_id: 9287645ztiu234jgk2j3g5jh,
outside: {
  temperature: 'low',            // 'low' or 'high'
  humidity: 'high',              // 'low' or 'high'
},
... some more fields

temperaturehumidity可以有lowhigh

我想计算在集合的每个文档中出现temperature: lowtemperature: highhumidity: lowhumidity: high的次数,因此查询结果如下: 14份文件应如下所示:

{
  temperatureLow: 2,
  temperatureHigh: 12,
  humidityLow: 8,
  humidityHigh: 6,
}

我尝试了$group(作为聚合管道中的唯一阶段),如下所示:

$group: {
  _id: { temperature: '$outside.temperature', humidity: '$outside.humidity' },
  count: { $sum: 1 },
},

这给了我这些文件(EDITED,第一篇文章有​​错误的数据):

{
    "_id": {
      "temperature": "high",
      "humidity": "high"
    },
    "count": 6
  },
  {
    "_id": {
      "temperature": "high",
      "humidity": "low"
    },
    "count": 6
  },
  {
    "_id": {
      "temperature": "low",
      "humidity": "low"
    },
    "count": 2
  }

如何将其合并到文档中?

1 个答案:

答案 0 :(得分:1)

这是可能的。您需要在project之前使用cont运算符添加group阶段:

{
    $project: {
        "temperatureLow": { $cond: { if: { $eq: ["$outside.temperature", "low"] }, then: 1, else: 0 }}, 
        "temperatureHigh": { $cond: { if: { $eq: ["$outside.temperature", "high"] }, then: 1, else: 0 }}, 
        "humidityLow": { $cond: { if: { $eq: ["$outside.humidity", "low"] }, then: 1, else: 0 }}, 
        "humidityHigh": { $cond: { if: { $eq: ["$outside.humidity", "high"] }, then: 1, else: 0 }}
    }
}, 
{
    $group: {
      _id: "result",
      "temperatureLow": {$sum: "$temperatureLow"},
      "temperatureHigh": {$sum: "$temperatureHigh"},
      "humidityLow": {$sum: "$humidityLow"},
      "humidityHigh": {$sum: "$humidityHigh"},
    }
},

<强>更新

或作为注释Neil Lunn我可以在cond运算符内使用sum而不使用project阶段:

{
    $group: {
      _id: "result",
    "temperatureLow": {$sum: { $cond: { if: { $eq: ["$outside.temperature", "low"] }, then: 1, else: 0 }}}, 
    "temperatureHigh": {$sum: { $cond: { if: { $eq: ["$outside.temperature", "high"] }, then: 1, else: 0 }}}, 
    "humidityLow": {$sum:{ $cond: { if: { $eq: ["$outside.humidity", "low"] }, then: 1, else: 0 }}}, 
    "humidityHigh": {$sum:{ $cond: { if: { $eq: ["$outside.humidity", "high"] }, then: 1, else: 0 }}}          
    }
},