【问题标题】:Use output from one aggregation pipeline stage in condition for the next stage将一个聚合管道阶段的输出用于下一阶段
【发布时间】:2019-03-03 11:32:52
【问题描述】:

是否可以使用聚合阶段的字段来过滤未来阶段的数据?

我有这个查询,我在其中进行匹配然后查找。我正在使用 mongodb 3.4,所以我无法使用条件过滤查找。我想做的是在查找后使用过滤器进行匹配或项目,以便我可以进一步过滤类集合中的文档。

在这种情况下,第一个集合有一个学生 ID,因此 $lookup 匹配 classes 集合中的学生 ID。问题是单个 studentID 可以有多个类,并且 $lookup 会拉回所有类。我想使用匹配中的数据进行进一步过滤,以便为每个学生拉回一个班级。

    collection.aggregate([
        {$match: {"field1": "value"}},
        {
            $lookup: {
               from: "classes",
               localField: "studentId",
               foreignField: "student._id",
               as: "classes"
            }
        },
        //filter with a match
        {
            $match: {
                "classes.field1": "$field1value", //$field1value is a field from the first collection
            }
        }
        //or filter with project and condition
        { 
            $project: {
                class: {
                    filter: {
                        input: "classes",
                        as: "class",
                        cond: {$eq: ['$$class.field1', "$classes.field1value"]}
                    }
                }
            }
        }
    ])

【问题讨论】:

  • 请提供样本数据和预期输出

标签: mongodb aggregation-framework


【解决方案1】:

使用pipeline 查找。以下查询将起作用:

collection.aggregate([
  { $match: { "field1": "value" } },
  { $lookup: {
    from: "classes",
    let: [studentId: "$studentId", field1value: "$field1value"],
    pipeline: [{ $match: {
      $expr: { 
        $and: [
          { $eq: ["$_id", "$$studentId"] },
          { $eq: ["$field1", "$$field1value"] },
        ]
      },
    } }],
    as: "classes",
  } }
]);

我希望这会有所帮助。

【讨论】:

  • 管道是否适用于 mongodb 3.4 还是需要更高版本?
  • 它需要更高版本。它是在 3.6 中引入的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 2020-05-08
相关资源
最近更新 更多