Nguyen Phuc Hai
Nguyen Phuc Hai

Reputation: 21

Mongodb : elemMatch

My problem cans be described as the following.

Give the following data (copied from mongo manual), how can i find the document which has zipcode 63109 and has 2 studends named "John", and "Jeff". I try

db.schools.find( { zipcode: 63109 }, { students: { $elemMatch: { name : {"John", "Jeff"} } } } )

But it doesn't work. Could you help me, please ? Thank you in advanced

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

Upvotes: 0

Views: 181

Answers (1)

viktortnk
viktortnk

Reputation: 2757

I don't think it's possible to use $elemMatch here

The only solution I see is:

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

Upvotes: 2

Related Questions