2

I am using Node.js, Koa, MongoDB, Monk.

When I use $elemMatch in query, it works fine but in projection it is getting ignored.

I have data like this

{
 _id: 1,
 zipcode: "63109",
 students: [
              { studentId: "1", name: "john", school: 102, age: 10 },
              { studentId: "2", name: "jess", school: 102, age: 11 },
              { studentId: "3", name: "jeff", school: 108, age: 15 }
           ]
}
{
 _id: 2,
 zipcode: "63110",
 students: [
              { studentId: "1", name: "john", school: 102, age: 10 },
              { studentId: "4", name: "achilles", school: 100, age: 8}
           ]
}
{
 _id: 3,
 zipcode: "63109",
 students: []
}
{
 _id: 4,
 zipcode: "63110",
 students: [
              { studentId: "3", name: "jeff", school: 108, age: 15 }
           ]
}

And I want:

documents having "zipcode" : "63109"

and students array should contain only that subdocument where 'studentId' is '2' (if it exists).

i.e. I want this :

{
 _id: 1,
 zipcode: "63109",
 students: [
              { studentId: "2", name: "jess", school: 102, age: 11 }
           ]
}
{
 _id: 3,
 zipcode: "63109",
 students: []
}

But I am getting every subdocument in "students" array. Seems like $elemMatch projection is getting ignored.

Query I am using:

collection.find({"zipcode":"63109"}, {students:{$elemMatch:{studentId:"2"}}})

Is there any way to achieve this ?

P.S. I am using co-monk.

  • 1
    the query is returning the correct result. what was the expected result? – Alvaro Silvino Sep 06 '15 at 13:06
  • possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – styvane Sep 06 '15 at 13:27

0 Answers0