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

145
Vistas
MongoDB/ Mongoose, A has many B, B has many C, find all C that indirectly belong to A

I have collection A, collection B and collection C. Collection A has many B and B has many C ( B has A primary key as a field, and C has B primary key as field).

Something like this

class A {
 //fields
}

class B {
a_id
}

class C {
b_id
}

I want to get all C that corresponds to A, eg I want to match all C's where the B they belong to, belongs to certain A.

If I have A id, I want to get all of the C's that indirectly belong to this A. Using mongoose and MongoDB

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do it with Aggregation Framework:

  • $lookup - to find B documents that are linked in C documents
  • $lookup - to find A documents that are linked in B documents
  • $match - to filter only document for requested A_id
  • $project - to select fields that you want to return
db.C.aggregate([
  {
    "$lookup": {
      "from": "B",
      "localField": "b_id",
      "foreignField": "_id",
      "as": "b"
    }
  },
  {
    "$lookup": {
      "from": "A",
      "localField": "b.a_id",
      "foreignField": "_id",
      "as": "a"
    }
  },
  {
    "$match": {
      "a._id": 1
    }
  },
  {
    "$project": {
      "_id": 1,
      "name": 1
    }
  }
])

Working example

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