ReDEyeS
ReDEyeS

Reputation: 851

MongoDB (Mongoose) how to returning all document fields using $elemMatch

According with MongoDB documentation (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 },
           ]
}

launching:

schools.find({ zipcode: 63109}, {students: { $elemMatch: { school: 102 } } }, function (err, school) { ...}

The operation returns the following documents:

{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] } { "_id" : 3 } { "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }

But I need the value of school filed too...

{ "_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", "school" : 102, "age" : 7 } ] }

and I can't find a way to achieve this...

Upvotes: 1

Views: 1131

Answers (2)

Talha Noyon
Talha Noyon

Reputation: 854

According to mongodb [documentation][1] $elemMatch return first matching element from an array based on a condition. So you have to use $filter instead of $elemMatch to get all matching element.

I have written a solution. please take a look. solution checkup link: https://mongoplayground.net/p/cu7Mf8XZHDI

db.collection.find({},
{
  students: {
    $filter: {
      input: "$students",
      as: "student",
      cond: {
        $or: [
          {
            $eq: [
              "$$student.age",
              8
            ]
          },
          {
            $eq: [
              "$$student.age",
              15
            ]
          }
        ]
      }
    }
  }
})



  [1]: http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/

Upvotes: 0

ReDEyeS
ReDEyeS

Reputation: 851

http://docs.mongodb.org/manual/reference/method/db.collection.find/

If the projection argument is specified, the matching documents contain only the projection fields and the _id field. You can optionally exclude the _id field.

but... I forced the Fields to Return using:

schools.find({ zipcode: 63109}, {school: 1, students: { $elemMatch: { school: 102 } } }, function (err, school) { ...}

and all seems to work properly...

Upvotes: 2

Related Questions