$Lookup 聚合嵌套数组元素

$Lookup nested array element in aggregate

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

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

Collection students

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

Collection 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

演示

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

FieldPath field names may not contain '.'.

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

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

但这只是解决了你的错误,还有另一个问题 enrollment 是一个数组,当我们检查字段 enrollment.studentID 的任何条件时,将 return id 数组,所以你可以使用 $in代替$eq,

最终解决方案是,

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

Playground