Home > Software engineering >  MongoDB - Get data in date sections from an array
MongoDB - Get data in date sections from an array

Time:05-17

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. :)

CodePudding user response:

  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.date",
      messages: 1
    }
  }
])

Sample Mongo Playground

  • Related