我有集合 A、集合 B 和集合 C。集合 A 有很多 B,B 有很多 C(B 有 A 主鍵作為欄位,C 有 B 主鍵作為欄位)。
像這樣的東西
class A {
//fields
}
class B {
a_id
}
class C {
b_id
}
我想獲取與 A 對應的所有 C,例如,我想匹配它們所屬的 B 屬于某個 A 的所有 C。
如果我有 A id,我想獲得所有間接屬于這個 A 的 C。使用 mongoose 和 MongoDB
uj5u.com熱心網友回復:
您可以使用聚合框架來做到這一點:
$lookup- 查找在 C 檔案中鏈接的 B 檔案$lookup- 查找在 B 檔案中鏈接的 A 檔案$match- 僅過濾請求的A_id的檔案$project- 選擇要回傳的欄位
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
}
}
])
作業示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447315.html
標籤:javascript 节点.js 打字稿 mongodb 猫鼬
下一篇:如何解決“CastError:CasttoObjectIdfailedforvalue"undefined"(typestring)atpath"_id"for
