1

I have two collects students and classes, and I want to query the all students with their free classes.

Mongo Playground at 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"
        }
      ]
    }
  ]

My Query:

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

But it gives me the error FieldPath field names may not contain '.'.

Also demonstrate at https://mongoplayground.net/p/WwON7lHbAvn

Many thanks for any help or suggestion.

1 Answer 1

1

FieldPath field names may not contain '.'.

The error comes from $expr: { "enrollment.studentID": "$$id" }, this is invalid syntax for $expr, to fix this,

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

But this just resolved your error, there is another issue the enrollment is an array and when we check any condition with field enrollment.studentID will return array of ids, so you can use $in instead of $eq,

Final solution is,

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

Playground

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.