document中可以内嵌document,
document中也可以有数组,
如果document的数组中是document又是什么情况,
例如有个school的collection有如下的document
{ _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: 102, age: 8 }, ] } { _id: 3, zipcode: "63109", students: [ { name: "jimi", school: 100, age: 8 }, { name: "messi", school: 102, age: 7 }, ] } { _id: 4, zipcode: "63109", students: [ { name: "barney", school: 102, age: 7 }, ] }
db.schools.find({'students.age':7}) 结果显示_id为2,3,4的三条记录 db.schools.find({'students.0.age':7}) 结果显示_id为2,4的两条记录 db.schools.find({'students.age':7,'students.school':100}) 结果显示_id为2,3的两条记录 和想象中结果是_id=2一条记录不一样
这时 该$elemMatch出场了
db.schools.find( { students:{ $elemMatch:{age:7,school:100} } } )
$elemMatch还有一种用法,用在第二个参数中
db.schools.find( { zipcode: "63109" }, { students: { $elemMatch: { school: 102 } } } )
db.schools.find( { zipcode: "63109" }, { students: { $elemMatch: { school: 102, age: { $gt: 10} } } } )
db.schools.find( { zipcode: 63109 }, { students: { $elemMatch: { school: 102 } } } ).sort( { "students.age": -1 } ) //age倒序