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

255
Views
How to transform an array of one value into an object in $project stage?

Using mongodb, I would like to transform an array in a a document that looks like this:

{activities: [{"start": start_date, "end": end_date, value:"4332A"}]}

Into an object, like this (only projecting the value field as the value of "activities"):

{activities: "4332A"}

I have tried using $arrayToObject in the $project stage, but the results is not really what I am looking for :

    db.companies.aggregate([{
        $project: {
            $map: {
                'input': '$activities',
                'as': 'item',
                'in': {
                    'k': 'activities',
                    'v': '$$item.value'
                }
            }
        }
    ])

The output being:

{"activities": {"activities": "4332A"}}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Assuming there is always exactly one result in the array ( as you said ), you can just use arrayElemAt, like so:

db.collection.aggregate([
  {
    $addFields: {
      activities: {
        "$arrayElemAt": [
          "$activities.value",
          0
        ]
      }
    }
  }
])

Mongo Playground

over 4 years ago · Santiago Trujillo 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!