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

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

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 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