我有一组文档,其中每个文档都有一个带有两个值的nestes字段outside
:
_id: 9287645ztiu234jgk2j3g5jh,
outside: {
temperature: 'low', // 'low' or 'high'
humidity: 'high', // 'low' or 'high'
},
... some more fields
temperature
和humidity
可以有low
或high
我想计算在集合的每个文档中出现temperature: low
,temperature: high
,humidity: low
,humidity: 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
}
如何将其合并到文档中?
答案 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 }}}
}
},