Charles Fonseca
Charles Fonseca

Reputation: 140

Group documents in two by array field Mongo Aggregation

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')
}

Upvotes: 0

Views: 30

Answers (1)

rickhg12hs
rickhg12hs

Reputation: 11912

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.

Upvotes: 1

Related Questions