Home > Blockchain >  Aggregation mongodb grouping by a value
Aggregation mongodb grouping by a value

Time:03-23

I have the followings documents of a mongodb collection:

{
"year": 2020,
"cod": 4241,
"op": "12"
}

{
"year": 2021,
"cod": 2241,
"op": "34"
}

{
"year": 2020,
"cod": 4325,
"op": "54"
}

{
"year": 2021,
"cod": 1132,
"op": "A3"
}

I need an aggregator that let me group these documents by the year, in this way:

{
"year": 2020,
"values": [{"cod":4241, "op":"12"}, {"cod":4325, "op":"54"}]
}

{
"year": 2021,
"values": [{"cod":2241, "op":"34"}, {"cod":1132, "op":"A3"}]
} 

CodePudding user response:

Something like this:

db.collection.aggregate([
{
$group: {
  _id: "$year",
  values: {
    $push: {
      cod: "$cod",
      op: "$op"
    }
  }
 }
},
{
 $project: {
  year: "$_id",
  values: 1,
  _id: 0
 }
}
])

playground

  • Related