Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda