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

254
Views
how to create a key value pair from fields in mongodb?

i have some data structured like this :

        "location_identifiers": [
            {
                "permalink": "olivette-missouri",
                "uuid": "e1774b1c-634d-4ea4-1414-cd8be15df631",
                "location_type": "city",
                "entity_def_id": "location",
                "value": "Olivette"
            },
            {
                "permalink": "missouri-united-states",
                "uuid": "51a065b8-05d5-1a28-3fcd-1ad143f1f725",
                "location_type": "region",
                "entity_def_id": "location",
                "value": "Missouri"
            }

i want to restructure it to look like this, i am using mongodb compass:

"location_identifiers": [
            {
                "city": "Olivette",
                "region": "Missouri"
            }
]

i have tried unwind and project query but i am stuck, any help would be greatly appreciated.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Use $arrayToObject

db.collection.aggregate([
  {
    "$match": {}
  },
  {
    "$set": {
      "location_identifiers": [
        {
          "$arrayToObject": {
            "$map": {
              "input": "$location_identifiers",
              "as": "item",
              "in": {
                k: "$$item.location_type",
                v: "$$item.value"
              }
            }
          }
        }
      ]
    }
  }
])

mongoplayground

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!