根据MongoDB文档(http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/):
{
_id: 1,
school: "school A",
zipcode: 63109,
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
{
_id: 2,
school: "school B",
zipcode: 63110,
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 3,
school: "school C",
zipcode: 63109,
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 4,
school: "school D",
zipcode: 63109,
students: [
{ name: "barney", school: 102, age: 7 },
]
}
发射:
schools.find({zipcode:63109},{students:{$ elemMatch:{school:102 },} function(err,school){...}
该操作返回以下文档:
{“_ id”:1,“学生”:[{“name”:“john”,“school”:102,“age”: 10}]} {“_ id”:3} {“_ id”:4,“学生”:[{“name”: “barney”,“school”:102,“age”:7}]}
但我也需要提交学校的价值......
{“_ id”:1,“学校”:“学校A”,“学生”:[{“姓名”:“约翰”,“学校”:102,“年龄”: 10}]} {“_ id”:3,“school”:“School C”} {“_ id”:4,“school”:“School D”,“students”:[{“name”: “barney”,“school”:102,“age”:7}]}
我无法找到实现这个目标的方法......
答案 0 :(得分:2)
http://docs.mongodb.org/manual/reference/method/db.collection.find/
如果指定了投影参数,则匹配文档 仅包含投影字段和_id字段。您可以 可选地排除_id字段。
但是......我强迫使用字段返回:
schools.find({ zipcode: 63109}, {school: 1, students: { $elemMatch: { school: 102 } } }, function (err, school) { ...}
所有似乎都正常工作......