MongoDB aggregation - project field values ​​as fields

Some problems getting my data in a complex format.

Documents have the following fields: subject, importance [high,medium,low]

sample document:

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

I like to return data that looks like this:

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

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

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"
       }
     }
   }
 }

Is there a way that I can use a value $_id.importanceand make it a key and have $countas a value?

+4
source share
1 answer

You can fill in as below:

  • $group subjectand importance, get the appropriate values.
  • , $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 }
+1

Source: https://habr.com/ru/post/1620938/


All Articles