Mongo查询:GraphLookup或聚合

时间:2018-07-30 03:47:38

标签: mongodb

寻找有关如何为图形网络可视化构造mongo查询的方向。

我有一个看起来像这样的数据模型:

stories[
{
  story: "story 1",
  theme_ids: [1,2,3],
  author_ids: [a,b,c]
},
{
  story: "story 2",
  theme_ids: [4],
  author_ids: [a]
}
...
]

我希望查询结果能够像这样抓住所有主题对和作者:

[
{from: 1, to: a},
{from: 1, to: b},
{from: 1, to: c},
{from: 2, to: a},
{from: 2, to: b},
{from: 2, to: c},
{from: 3, to: a},
{from: 3, to: b},
{from: 3, to: c},
{from: 4, to: a}
]

谢谢! MongoDB v3.4

1 个答案:

答案 0 :(得分:1)

您可以使用双$unwind来获取所有对:

db.col.aggregate([
    {
        $project: {
            from: "$theme_ids",
            to: "$author_ids"
        }
    },
    {
        $unwind: "$from"
    },
    {
        $unwind: "$to"
    }
])

如果您需要删除重复项,则可以将$group$addToSet添加:

{
    $group: {
        _id: null,
        uniquePairs: { $addToSet: "$$ROOT" }
    }
}