Home > Net >  How to get subdocument without root document?
How to get subdocument without root document?

Time:04-18

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?

CodePudding user response:

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);
  • Related