我将使用此处的示例
{
_id: 1,
zipcode: 63109,
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
{
_id: 2,
zipcode: 63110,
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 3,
zipcode: 63109,
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 4,
zipcode: 63109,
students: [
{ name: "barney", school: 102, age: 7 },
]
}
如果我跑
db.schools.find( { zipcode: 63109 },
{ students: { $elemMatch: { school: 102 } } } )
它将给出每个数组的第一个结果。命名为:
{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }
我怎样才能让它返回符合条件的数组的所有对象(而不仅仅是第一个对象)?这意味着:
{
_id: 1,
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 }
]
}
{ _id: 3 }
{_id: 4, students: [ { name: "barney", school: 102, age: 7 }]}