我有两个集合students
和classes
,我想查询所有有免费课程的学生。
Mongo游乐场https://mongoplayground.net/p/WwON7lHbAvn
集合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
非常感谢您的帮助或建议。
FieldPath字段名不能包含".">
错误来自$expr: { "enrollment.studentID": "$$id" }
,这是$expr
的无效语法,要解决此问题,
$expr: { $eq: ["$enrollment.studentID", "$$id"] }
但这只是解决了您的错误,还有另一个问题,enrollment
是一个数组,当我们用字段enrollment.studentID
检查任何条件时,都会返回ID的数组,所以您可以使用$in
而不是$eq
,
最终解决方案是,
$expr: { $in: ["$$id", "$enrollment.studentID"] }
游乐场