Home > Enterprise >  MongoDB/ Mongoose, A has many B, B has many C, find all C that indirectly belong to A
MongoDB/ Mongoose, A has many B, B has many C, find all C that indirectly belong to A

Time:03-20

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

CodePudding user response:

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
  • $match - 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

  • Related