我们从 mongoDB 获取了一个集合,文档架构如下
{
"_id": {
"$oid": {
"type": "ObjectId"
}
},
"name": {
"type": "String"
},
"_parentOrg": {
"$oid": {
"type": "ObjectId"
}
},
}
我们已经知道,该文档的设计类似于树形结构。可能没有父母,或者可能有祖父母,或曾祖父母,也许更多。
如何编写查询以获得如下所示的内容:
organization_name:xxx,
organization_id:yyy,
childrens_org_ids : [a,b,c,...]
这样我就可以创建一个函数来制作类似于组织结构的功能。
==============
ChatGPT 给了我类似下面的内容,这是不正确的,因为所有 childs_id 都是空数组。
db.getCollection("org").aggregate([
{
$lookup: {
from: "organizations",
localField: "_id",
foreignField: "_parentOrg",
as: "children",
},
},
{
$project: {
organization_name: "$name",
organization_id: "$_id",
childrens_org_ids: "$children._id",
},
},
]);