我對貓鼬很陌生,我想知道是否可以根據孫子財產進行過濾。我到處尋找,但無法根據我正在嘗試做的事情找到類似的問題。這是場景:
想象一下我有一個這樣的資料庫:
db={
"parents": [
{
"_id": ObjectId("5a834e000102030405000000"),
"child": ObjectId("5a934e000102030405000000")
},
{
"_id": ObjectId("5a834e000102030405000001"),
"child": ObjectId("5a934e000102030405000001")
},
{
"_id": ObjectId("5a834e000102030405000002"),
"child": ObjectId("5a934e000102030405000002")
},
],
"children": [
{
"_id": ObjectId("5a934e000102030405000000"),
"grandchild": ObjectId("5a734e000102030405000000")
},
{
"_id": ObjectId("5a934e000102030405000001"),
"grandchild": ObjectId("5a734e000102030405000001")
},
{
"_id": ObjectId("5a934e000102030405000002"),
"grandchild": ObjectId("5a734e000102030405000002")
}
],
"grandchildren": [
{
"_id": ObjectId("5a734e000102030405000000"),
"name": "grandchild1"
},
{
"_id": ObjectId("5a734e000102030405000001"),
"name": "grandchild2"
},
{
"_id": ObjectId("5a734e000102030405000002"),
"name": "grandchild3"
}
]
}
我想回傳所有有一個名為“grandchild1”的孫子的父母。
類似的東西
$match: {
"child.grandchild.name": "grandchild1"
}
所以只有這個父級會在結果中回傳——
[{
"_id": ObjectId("5a834e000102030405000000"),
"child": ObjectId("5a934e000102030405000000")
},]
uj5u.com熱心網友回復:
我在任何人回應之前找到了答案......
https://mongoplayground.net/p/w1kw58PzCyk
db.parents.aggregate([
{
$lookup: {
from: "children",
localField: "child",
foreignField: "_id",
as: "child",
}
},
{
$addFields: {
child: {
$arrayElemAt: [
"$child",
0
]
}
}
},
{
"$lookup": {
from: "grandchildren",
localField: "child.grandchild",
foreignField: "_id",
as: "grandchild",
}
},
{
$addFields: {
grandchild: {
$arrayElemAt: [
"$grandchild",
0
]
}
}
},
{
$match: {
"grandchild.name": "grandchild1"
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360074.html
