Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda