【问题标题】:Mongo Query: GraphLookup or AggregateMongo 查询:GraphLookup 或 Aggregate
【发布时间】:2018-07-30 13:49:50
【问题描述】:

寻找有关如何为图形网络可视化构建 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

【问题讨论】:

  • 还想从结果集中删除重复项。

标签: mongodb


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多