Search code examples
mongodbaggregate

MongoDb group by two conditions in aggregate


I would like to group my data by different conditions but I do not understand how I could do it.

My data:

[
 {"Id": "1", "Info": "X" "Date": 10/1},
 {"Id": "2", "Info": "X" "Date": 13/2},
 {"Id": "3", "Info": "Y" "Date": 13/2},
 {"Id": "4", "Info": "X" "Date": 10/1},
 {"Id": "5", "Info": "X" "Date": 10/1},
 {"Id": "6", "Info": "X" "Date": 13/2},
]

And I would like to group them by Info and by Date, a result similar to this one:

[
 {"Id": ["1","4","5"], "Info": "X" "Date": 10/1},
]
[ 
 {"Id": ["2", "6"], "Info": "X" "Date": 13/2},
 ]   
[
 {"Id": ["3"], "Info": "Y" "Date": 13/2},
]

I am using aggregate and I just know how to use aggregate to group them just by one condition, I don´t know how to continue and how to use date in $group, this is what I have and how I group it by info:

.aggregate([
            { "$match" : { "$or": [{"status": "downloading"}, {"status": "calculating"}]}},
            { "$project": {"Id": 1, "Date": 1, "info": 1}},
            { "$group" : { "_id" : "$Info", "Id" : { "$addToSet" : "$Id"}}},
            { "$project": {"_id": 0, "Info": "$_id", "Id": 1 }}

Solution

  • You can give the _id in the $group stage multiple fields, like so:

    db.collection.aggregate([
      {
        "$project": {
          "Id": 1,
          "Date": 1,
          "info": 1
        }
      },
      {
        "$group": {
          "_id": {
            date: "$Date",
            info: "$info"
          },
          "Id": {
            "$addToSet": "$Id"
          }
        }
      },
      {
        "$project": {
          "_id": 0,
          "Info": "$_id.info",
          "Date": "$_id.date",
          "Id": 1
        }
      }
    ])
    

    Mongo Playground