【发布时间】:2022-01-14 16:15:40
【问题描述】:
考虑一下,我有以下代表树结构的文档:
[
{
"_id": 1,
"parentId": null,
},
{
"_id": 2,
"parentId": null,
},
{
"_id": 3,
"parentId": 1,
},
{
"_id": 4,
"parentId": 1,
},
{
"_id": 5,
"parentId": 2,
},
{
"_id": 6,
"parentId": 5,
},
]
使用 MongoDB 聚合计算这些树的深度分布的最高效方法是什么?
我希望收到以下或类似的结果:
[
{
"depth": 0,
"count": 2,
},
{
"depth": 1,
"count": 3,
},
{
"depth": 2,
"count": 1,
}
]
所有count 的总和应该等于集合中的文档数。
我尝试使用各种聚合函数的组合,但只设法在不考虑根节点的情况下计算数据:
db.collection.aggregate([
{
// Skipping the root nodes,
// otherwise it will calculate results
// for all the nodes and count them multiple times
$match: {
parentId: null
}
},
{
$graphLookup: {
from: "collection",
startWith: "$_id",
connectFromField: "_id",
connectToField: "parentId",
as: "descendants",
depthField: "depth",
},
},
{
$unwind: "$descendants",
},
{
$group: {
_id: "$descendants.depth",
count: {
$sum: 1,
},
},
},
{
$project: {
_id: 0,
depth: "$_id",
count: "$count",
},
},
{
$sort: {
depth: 1,
},
},
]);
这是带有示例数据的Mongo Playground。
【问题讨论】:
标签: javascript mongodb mongodb-query aggregate query-optimization