Group documents in two by array field Mongo Aggregation

Issue

How do I group the date field one to the next one in each document?

{
  _id: ObjectId('...'),
  date: [ISODate('2022-05-27T00:00:00.000+00:00'), ISODate('2022-05-28T00:00:00.000+00:00') ...]
}

The desired document would like this:

{
  _id: ObjectId('...'),
  date1: ISODate('2022-05-27T00:00:00.000+00:00'),
  date2: ISODate('2022-05-28T00:00:00.000+00:00')
}

Solution

Here’s one way to do it.

db.collection.aggregate([
  { "$replaceWith": {
      "$mergeObjects": [
        { "_id": "$_id" },
        { "$arrayToObject": {
            "$map": {
              "input": { "$range": [ 0, { "$size": "$date" } ] },
              "as": "dateNum",
              "in": {
                "k": {
                  "$concat": [
                    "date",
                    { "$toString": { "$add": [ "$$dateNum", 1 ] } }
                  ]
                },
                "v": { "$arrayElemAt": [ "$date", "$$dateNum" ] }
              }
            }
          }
        }
      ]
    }
  }
])

Try it on mongoplayground.net.

Answered By – rickhg12hs

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.