2014-01-13 137 views
1

返回所有文件中的字段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({邮编:63109},{学生:{$ elemMatch:{school:102 }}},function(err,school){...}

该操作返回以下文档:

{ “_id”:1, “生”:[{ “名称”: “约翰”, “学校”:102, “年龄”: 10}]} { “_id”:3} { “_id”:4, “学生”:[{ “Name”: “巴尼”, “学校”:102, “时代”:7}]}

但我需要学校的价值提交过...

{“_id”:1,“school”:“School A”,“students”:[{“name”:“john”,“school”:102,“age” : 10}]} {“_id”:3,“school”:“School C”} {“_id”:4,“school”:“School D”,“students”:[{“name”: “barney ”, “学校”:102, “时代”:7}]}

,我无法找到一个方法来做到这一点...

回答

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) { ...} 

和一切似乎正常工作...