1

I have a collection similar to this:

[
  {
    "_id":1,
    "name":"breakfast",
    "time":"10.00"
  },
  {
    "_id":3,
    "name":"lunch",
    "time":"12.07"
  },
  {
    "_id":2,
    "name":"breakfast",
    "time":"10.10"
  },
  {
    "_id":4,
    "name":"lunch",
    "time":"12.45"
  }
]

I want to aggregate into something like this:

{
  "breakfast":[
    {
      "_id":1,
      "name":"breakfast",
      "time":"10.00"
    },
    {
      "_id":2,
      "name":"breakfast",
      "time":"10.10"
    }
  ],
  "lunch":[
    {
      "_id":3,
      "name":"lunch",
      "time":"12.07"
    },
    {
      "_id":4,
      "name":"lunch",
      "time":"12.45"
    }
  ]
}                

I have only managed to group them but I can't change the key meals to either breakfast or lunch depending on the meal.name(group name)

$group: {
    _id: { meal: '$meal.name' },
    meals: { $push: '$meal' },
}

Using the above code I have managed to produce the output below. My only challenge is changing the key meals to either breakfast or lunch as explained above in the subgroups.

{
  "meals":[
    {
      "_id":1,
      "name":"breakfast",
      "time":"10.00"
    },
    {
      "_id":2,
      "name":"breakfast",
      "time":"10.10"
    }
  ],
  "meals":[
    {
      "_id":3,
      "name":"lunch",
      "time":"12.07"
    },
    {
      "_id":4,
      "name":"lunch",
      "time":"12.45"
    }
  ]
}

1 Answer 1

2

Here you can have your answer .
After "grouping" to add to an array you similarly $push all that content into array by the "name" grouping key and then convert into keys of a document in a $replaceRoot with $arrayToObject:

db.collection.aggregate([
  { "$group": {
    "_id": "$name",
    "data": { "$push": "$$ROOT" }
  }},
  { "$group": {
    "_id": null,
    "data": {
      "$push": {
        "k": "$_id",
        "v": "$data"
      }
    }
  }},
  { "$replaceRoot": {
    "newRoot": { "$arrayToObject": "$data" }
  }}
])

OUTPUT

[
  {
    "breakfast": [
      {
        "_id": 1,
        "name": "breakfast",
        "time": "10.00"
      },
      {
        "_id": 2,
        "name": "breakfast",
        "time": "10.10"
      }
    ],
    "lunch": [
      {
        "_id": 3,
        "name": "lunch",
        "time": "12.07"
      },
      {
        "_id": 4,
        "name": "lunch",
        "time": "12.45"
      }
    ]
  }
]

You can check the result of above query in this LINK

Sign up to request clarification or add additional context in comments.

1 Comment

Precise and optimal approach :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.