Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

56
Views
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')
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!