Mongodb:elemMatch

时间:2013-09-25 21:51:40

标签: mongodb

我的问题可以描述如下。

提供以下数据(从mongo手册复制),如何找到包含邮编63109并且有2个名为“John”和“Jeff”的学生的文档。我试试

db.schools.find({zipcode:63109},                  {学生:{$ elemMatch:{name:{“John”,“Jeff”}}}})

但它不起作用。请问你能帮帮我吗 ? 先谢谢你了

{
 _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 },
           ]
}

1 个答案:

答案 0 :(得分:1)

我认为不可能在这里使用$ elemMatch

我看到的唯一解决方案是:

db.schools.find( { zipcode: 63109, $and: [{"students.name": "john"}, {"students.name": "jeff"}]} )