$Lookup 聚合的嵌套数组元素

时间:2021-05-14 03:49:13

标签: mongodb aggregation-framework lookup

我有两个集合 studentsclasses,我想查询所有学生的免费课程。

https://mongoplayground.net/p/WwON7lHbAvn 的 Mongo 游乐场

集合students

[
    {
      "_id": 1,
      "name": "John"
    },
    {
      "_id": 2,
      "name": "Nancy"
    }
  ]

集合classes

[
    {
      type: "free",
      "enrollment": [
        {
          studentID: 1,
          other: "other value"
        }
      ]
    },
    {
      type: "common",
      "enrollment": [
        {
          studentID: 1,
          other: "other value"
        },
        {
          studentID: 2,
          other: "other value"
        }
      ]
    }
  ]

我的查询:

db.students.aggregate([
  {
    $lookup: {
      from: "classes",
      let: {
        id: "$_id"
      },
      pipeline: [
        {
          $match: {
            type: "free",
            $expr: {
              "enrollment.studentID": "$$id"
            }
          }
        }
      ],
      as: "freeclasses"
    }
  }
])

但它给了我错误 FieldPath field names may not contain '.'.

也在 https://mongoplayground.net/p/WwON7lHbAvn

演示

非常感谢您的任何帮助或建议。

1 个答案:

答案 0 :(得分:1)

<块引用>

FieldPath 字段名称不能包含“.”。

错误来自 $expr: { "enrollment.studentID": "$$id" },这是 $expr 的无效语法,要解决这个问题,

$expr: { $eq: ["$enrollment.studentID", "$$id"] }

但这只是解决了您的错误,还有另一个问题,enrollment 是一个数组,当我们检查带有字段 enrollment.studentID 的任何条件时,将返回 ID 数组,因此您可以使用{{1} } 而不是 $in,

最终的解决方案是,

$eq

Playground