将我的数据转换为棘手的格式时遇到了一些麻烦。
文档具有以下字段: subject, importance [high,medium,low]
样本文件:
{_id: "", subject: "red", importance: "high"}
我喜欢返回看起来像这样的数据:
[{_id: subject, high: 5, medium: 6, low: 3}]
数字与每个重要性级别对应的文档数相对应
这是我到目前为止所拥有的:
{
$group: {
_id: {subject: "$subject", importance: "$importance"},
count: {$sum: 1},
}
},
{
$group: {
_id: "$_id.subject",
data: {
$push: {
importance: "$_id.importance", count: "$count"
}
}
}
}
有没有一种方法可以使用的值$_id.importance
并将其作为键并具有$count
作为值?
您可以汇总如下:
$group
通过subject
和importance
,获得各自的计数。$project
它将相对于importance
字段可以容纳的选项数量线性增长。目前是三- high
,low
和medium
。$group
再次返回结果,subject
并使用$sum
运算符对accumulate
重要性字段的不同值进行计数。样例代码:
db.t.aggregate([
{$group:{"_id":{"subject":"$subject",
"importance":"$importance"},
"count":{$sum:1}}},
{$project:{"_id":0,
"subject":"$_id.subject",
"result":{$cond:[
{$eq:["$_id.importance","high"]},
{"high":"$count"},
{$cond:[{$eq:["$_id.importance","low"]},
{"low":"$count"},
{"medium":"$count"}]}]}}},
{$group:{"_id":"$subject",
"low":{$sum:"$result.low"},
"medium":{$sum:"$result.medium"},
"high":{$sum:"$result.high"}}},
])
测试数据:
db.t.insert([
{"subject":"history","importance":"high"},
{"subject":"geography","importance":"low"},
{"subject":"history","importance":"low"},
{"subject":"history","importance":"medium"},
{"subject":"geography","importance":"low"},
{"subject":"history","importance":"low"}
])
结果:
{ "_id" : "geography", "low" : 2, "medium" : 0, "high" : 0 }
{ "_id" : "history", "low" : 2, "medium" : 1, "high" : 1 }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句