skip to Main Content

I am new to MongoDB, I want to get data in sections from the array.

{
   "name":"User name",
   "messages":[
      {
         "message":"Message 1",
         "date":"2022-05-12T00:00:00.000Z"
      },
      {
         "message":"Message 2",
         "date":"2022-05-12T00:00:00.000Z"
      },
      {
         "message":"Message 3",
         "date":"2022-05-13T00:00:00.000Z"
      },
      {
         "message":"Message 4",
         "date":"2022-05-13T00:00:00.000Z"
      },
      {
         "message":"Message 5",
         "date":"2022-05-13T00:00:00.000Z"
      }
   ]
}

The results I want are

[
   {
      "date":"2022-05-12T00:00:00.000Z",
      "messages":[
         {
            "message":"Message 1",
            "date":"2022-05-12T00:00:00.000Z"
         },
         {
            "message":"Message 2",
            "date":"2022-05-12T00:00:00.000Z"
         }
      ]
   },
   {
      "date":"2022-05-13T00:00:00.000Z",
      "messages":[
         {
            "message":"Message 3",
            "date":"2022-05-13T00:00:00.000Z"
         },
         {
            "message":"Message 4",
            "date":"2022-05-13T00:00:00.000Z"
         },
         {
            "message":"Message 5",
            "date":"2022-05-13T00:00:00.000Z"
         }
      ]
   }
]

I’m not familiar with MongoDB aggregation, I have looked at many questions on stack overflow but didn’t find any that helped me.

Is this possible to do? If yes any help would be greatly appreciated. 🙂

2

Answers


    1. $unwind – Deconstruct messages array to multiple documents.
    2. $group – Group by messages.date and add messages document into messages array.
    3. $project – Decorate output documents.
    db.collection.aggregate([
      {
        $unwind: "$messages"
      },
      {
        $group: {
          _id: "$messages.date",
          messages: {
            $push: "$messages"
          }
        }
      },
      {
        $project: {
          _id: 0,
          date: "$_id",
          messages: 1
        }
      }
    ])
    

    Sample Mongo Playground

    Login or Signup to reply.
  1. You can use aggregation to get your desired output.

    db.collection.aggregate([
      {
        $unwind: "$messages"
      },
      {
        $group: {
          _id: "$messages.date",
          messages: {
            $push: "$messages"
          }
        }
      },
      {
        $project: {
          _id: 0,
          date: "$_id",
          messages: 1
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search