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

452
Views
how to replace the root with object value in MongoDB

Document 1:

{
  "data": {
    "id": "123456",
    "name": "abc",
    "value": 1
  }
}

Expected Output-

{
  "abc": {
    "id": "123456",
    "name": "abc",
    "value": 1
  }
}

Explanation: How we can replace the root with the " name" value, check the expected output, whatever value of the "name", it becomes on the root level. and I have multiple documents. Thanks in advance.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can achieve this via $project aggregation. It should be something like this:

{ $project: { "$data.name": "$data" } }
over 4 years ago · Santiago Trujillo Report

0

Mongo doesn't allow field names to start with a $ meaning you can't define a dynamic key name.

You'll have to work around this restriction by playing with the data structure, here is an example of how to achieve this with $arrayToObject

db.collection.aggregate([
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": [
          [
            {
              k: "$data.name",
              v: "$data"
            }
          ]
        ]
      }
    }
  }
])

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!