【问题标题】:Conditional from collection on $lookup in MongoDB aggregationMongoDB 聚合中 $lookup 集合的条件
【发布时间】:2021-02-22 22:52:55
【问题描述】:

假设我有四个集合:一个Main 集合和另外三个ABC

主集合有一个foreignKey 字段,它指向ABC 中的记录,具体取决于字段type

Main
{_id: 1, foreignKey: 1, type: "TypeA"},
{_id: 2, foreignKey: 2, type: "TypeA"},
{_id: 3, foreignKey: 1, type: "TypeB"},
{_id: 4, foreignKey: 1, type: "TypeC"}


A
{_id: 1, otherData: "asdf"},
{_id: 2, otherData: "qwer"}

B
{_id: 1, otherData: "hello"},

C
{_id: 1, otherData: "world"}

我想在聚合中使用 $lookup 执行连接。有没有办法让from 字段依赖于type 字段的值?

本例中的结果是:

{_id: 1, foreignKey: 1, type: "TypeA", rest: {_id: 1, otherData: "asdf"}},
{_id: 2, foreignKey: 2, type: "TypeA", rest: {_id: 1, otherData: "qwer"}},
{_id: 3, foreignKey: 1, type: "TypeB", rest: {_id: 1, otherData: "hello"}},
{_id: 4, foreignKey: 1, type: "TypeC", rest: {_id: 1, otherData: "world"}}

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    我不知道我是否理解得很好,但是……你是这个意思吗?

    db.Main.aggregate([
      {
        "$match": {
          "type": "TypeC"
        }
      },
      {
        "$lookup": {
          "from": "C",
          "localField": "foreignKey",
          "foreignField": "_id",
          "as": "output"
        }
      }
    ])
    

    $lookup 只使用您想要的类型而不是所有类型。

    例如here

    没有$match 阶段,输出包含所有类型(example

    【讨论】:

    • 谢谢。差不多了。我想要那个,但对于每种类型。喜欢做三个匹配并连接结果,比方说
    【解决方案2】:

    你不能在 $lookup 中做动态。您可以在这里做的是对每个集合(A、B、C)进行 3 个查找阶段,然后在下一个投影阶段,您将知道根据您的“类型”属性从哪个字段获取值。为了确保良好的性能,您还可以做的是在这些外键的 A、B 和 C 集合中创建索引。

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 2020-08-02
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多