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

166
Views
How to get subdocument without root document?

I have this json file

{
  "_id": "1",
  "name": "sanggiyo",
  "gender": "Male",
  "children": [
    {
      "name": "tono",
      "gender": "Male",
      "children": [],
      "_id": "2"
    },
    {
      "name": "rin",
      "gender": "Female",
      "children": [],
      "_id": "3"
    }
  ],
  "createdAt": "2022-04-17T11:14:00.648Z",
  "updatedAt": "2022-04-17T11:14:16.277Z",
  "__v": 0
}

I want to get children._id using

  Person.find( {$or: [ { "_id" : id }, { "children._id" : ObjectId(id) } ]} )

if I use id of 1, I should get all document. but if I use id of 2, I should only get that children object without id 1, is there a way to do it?

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

0

You can try doing with aggregation framework, but much more readable and maintainable way to do that is in the code after the mongo query returned similar to that:

const persons = await Person.find({$or: [ { "_id" : id }, { "children._id" : ObjectId(id) } ]});

const result = persons.flatMap(p => [p, ...p.children]).find(p => p._id === id);
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!