Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB merge Array Elements inside an Array

I have a collection.

{ 
    "_id" : "410a7cb2-7ee1-4e7a-9fb7-fa651fcaa4e5", 
    "reqHistoryEvents" : [
        {
            "reqHistoryMsg" : "abcd", 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:18:30.850+0000"), 
           
        }, 
        {
            "reqHistoryMsg" : "EFGH ", 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716+0000"), 
          
        }, 
        {
            "reqHistoryMsg" : "IJKL", 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716+0000"), 
        }
    ]
}

I want to convert it to this :::::

{ 
    "_id" : "410a7cb2-7ee1-4e7a-9fb7-fa651fcaa4e5", 
    "reqHistoryEvents" : [
        {
            "reqHistoryMsg" : "abcd", 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:18:30.850+0000"), 
           
        }, 
        {
            "reqHistoryMsg" : ["EFGH ","IJKL"], 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716+0000"), 
          
        }
    ]
}

Basically it will be based on the creation Timestamp. We need to merge the reqHistoryMsg if we have same reqHistoryCreatedAt.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am not able to write the mongo query. Any help?

>Solution :

  1. $unwind – Deconstruct reqHistoryEvents array field.
  2. $group – Group by _id and reqHistoryEvents.reqHistoryCreatedAt fields. Add reqHistoryMsg into an array.
  3. $group – Group by _id field and form reqHistoryEvents array.
db.collection.aggregate([
  {
    $unwind: "$reqHistoryEvents"
  },
  {
    $group: {
      _id: {
        _id: "$_id",
        reqHistoryCreatedAt: "$reqHistoryEvents.reqHistoryCreatedAt"
      },
      reqHistoryMsg: {
        $push: "$reqHistoryEvents.reqHistoryMsg"
      }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      reqHistoryEvents: {
        $push: {
          reqHistoryMsg: "$reqHistoryMsg",
          reqHistoryCreatedAt: "$_id.reqHistoryCreatedAt"
        }
      }
    }
  }
])

Sample Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading