我正在使用 Node.js、Koa、MongoDB、Monk。
当我在查询中使用 $elemMatch 时,它工作正常,但在投影中它被忽略了。
我有这样的数据
{
_id: 1,
zipcode: "63109",
students: [
{ studentId: "1", name: "john", school: 102, age: 10 },
{ studentId: "2", name: "jess", school: 102, age: 11 },
{ studentId: "3", name: "jeff", school: 108, age: 15 }
]
}
{
_id: 2,
zipcode: "63110",
students: [
{ studentId: "1", name: "john", school: 102, age: 10 },
{ studentId: "4", name: "achilles", school: 100, age: 8}
]
}
{
_id: 3,
zipcode: "63109",
students: []
}
{
_id: 4,
zipcode: "63110",
students: [
{ studentId: "3", name: "jeff", school: 108, age: 15 }
]
}
而且我要:
具有“邮政编码”的文件:“63109”
并且学生数组应仅包含“studentId”为“2”的子文档(如果存在)。
即我想要这个:
{
_id: 1,
zipcode: "63109",
students: [
{ studentId: "2", name: "jess", school: 102, age: 11 }
]
}
{
_id: 3,
zipcode: "63109",
students: []
}
但是我在“students”数组中获取了每个子文档。似乎 $elemMatch 投影被忽略了。
我正在使用的查询:
collection.find({"zipcode":"63109"}, {students:{$elemMatch:{studentId:"2"}}})
有没有办法做到这一点?
PS我正在使用co-monk。