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

183
Views
Mongodb Aggregate with nested subdocuments

I have a document looking like this:

{
  "_id": "some_uuid",
  "inv": {
    "food01": "id01",
    "food02": "id02",
    "food03": "id03"
  },
  "food": {
    "id01": {
      "n": "apple"
    },
    "id02": {
      "n": "banana"
    },
    "id03": {
      "n": "pear"
    }
  }
}

I want to use Mongodb Aggregate to retrieve the following output.

Expected Output

{
    "_id": "some_uuid",
  "inv": {
    "food01": "apple",
    "food02": "banana",
    "food03": "pear"
  }
}

Can someone guide me how to do this? Thank you!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

One option is using $objectToArray to format these fields as arrays, which will allow to use $map and $filter to match them:

db.collection.aggregate([
  {$set: {inv: {$objectToArray: "$inv"}, food: {$objectToArray: "$food"}}},
  {
    $project: {
      inv: {$map: {
          input: "$inv",
          in: {
            k: "$$this.k",
            v: {
              $filter: {
                input: "$food",
                as: "food",
                cond: {$eq: ["$$this.v", "$$food.k"]}
              }
            }
          }
        }
      }
    }
  },
  {
    $project: {
      inv: {
        $map: {
          input: "$inv",
          in: {k: "$$this.k", v: {$first: "$$this.v.v.n"}}
        }
      }
    }
  },
  {$project: {inv: {$arrayToObject: "$inv"}}}
])

See how it works on the playground example

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!