'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
Solution 1:[1]
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
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
