MongoDB聚合-项目字段值作为字段 [英] MongoDB aggregation - project field values as fields

查看:47
本文介绍了MongoDB聚合-项目字段值作为字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将我的数据转换为棘手的格式时遇到了麻烦.

Having some trouble getting my data into a tricky format.

文档具有以下字段:主题,重要性[高,中,低]

样本文档:

{_id: "", subject: "red", importance: "high"}

我想返回看起来像这样的数据:

I like to return data that looks like:

[{_id: subject, high: 5, medium: 6, low: 3}] 

数字与每个重要性级别的文档数相对应

The numbers correspond with the number of documents with each importance level

这是我到目前为止所拥有的:

This is what I have so far:

{
$group: {
  _id: {subject: "$subject", importance: "$importance"},
  count: {$sum: 1},
  }
 },
 {
   $group: {
     _id: "$_id.subject",
     data: {
       $push: {
          importance: "$_id.importance", count: "$count"
       }
     }
   }
 }

有没有一种方法可以使用 $ _ id.importance 的值并将其作为键并以 $ count 作为值?

Is there a way that I can use the value of $_id.importance and make that the key and have $count as the value?

推荐答案

您可以如下汇总:

  • $ group 通过 subject importance 分别获得计数.
  • 然后是棘手的部分,即条件 $ project ,它会相对于 importance 字段可以容纳的选项数量线性增长.当前是三个- high low medium .
  • $ group 通过 subject 重新返回结果,并使用
  • $group by subject and importance, get the respective counts.
  • Then comes the tricky part, the conditional $project, it would grow linearly with respect to the number of options the importance field could hold. currently it is three - high, low and medium.
  • $group the result back again by subject and use the $sum operator to accumulate the counts for the different values of the importance field.

示例代码:

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 }

这篇关于MongoDB聚合-项目字段值作为字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆