0

我在 MongoDB 集合中构建了一个关系图,例如:

{ "user_id": 1, "follower_id": 2 }
{ "user_id": 1, "follower_id": 3 }
{ "user_id": 2, "follower_id": 1 }
{ "user_id": 2, "follower_id": 3 }
{ "user_id": 3, "follower_id": 4 }
{ "user_id": 5, "follower_id": 2 }

这表示一个有向图,如下所示:

在此处输入图像描述

有没有一种有效的方法可以从图中删除“叶子”?在示例中,我想从图中删除节点 4,因为该节点只有一个与节点 3 的链接并删除节点 5,因为只有节点 2 链接到它。

或者用图形术语说:只保留入度 > 1 或出度 > 1 的顶点

4

1 回答 1

3

简短的回答是否定的 - 没有有效的方法可以用这样的模式来做你想做的事情。它可以通过迭代所有节点,例如使用聚合框架,并将节点作为单独的操作删除,但我认为这就是所有可以做的。假设节点在graph集合中,它可能如下所示,但远非有效:

db.graph.aggregate(
        {$project: {index: {$const: [0, 1]}, user_id: 1, follower_id: 1}},
        {$unwind: "$index"},
        {$project: {id: {$cond: [{$eq: ["$index", 0 ]}, "$user_id", "$follower_id"]} }},
        {$group: {_id: "$id", count: {$sum: 1}}},
        {$match: {count: {$lte: 1}}}
).result.forEach(function(node) { db.graph.remove({user_id: node._id});})

如果您希望这样的操作高效,您可以使用更多类似文档的模式。

{
    user_id: 1,
    follows: [2, 3],
    followed_by: [2]
}
于 2013-11-05T14:34:17.747 回答