elad BA
elad BA

Reputation: 1978

mongoose $elemMatch returns all results instead only the first

As I understand $elemMatch should find and return only the first elem` it encounters but instead it returns all the array, this is the DB data

{
    _id:  "123123123",
    "user_id": "0",
    "list": [
     {
        "employee_code": 1111,
        "list": []
     }, 
     {
        "employee_code": 2222,
        "list": []
     }
    ]
}

I want to return only the first elem'

this is my query:

Reports.find(
 {user_id:"123123123"},
 {"list":{$elemMatch:{"employee_code": 1111}}
})

I expect it to return only the first obj' list:[{employee_code:1111,...}] but instead it returns all the array

better ex:

enter image description here

Upvotes: 2

Views: 1152

Answers (2)

NeNaD
NeNaD

Reputation: 20334

$elemMatch will return document that contain an array field with at least one element that matches all the specified query criteria. You should use positional operator $ instead:

db.collection.find({
  "_id": "123123123",
  "list.employee_code": 1111
},
{
  "list.$": 1
});

Here is the working example: https://mongoplayground.net/p/gQvKniEVgfT

Upvotes: 1

mohammad Naimi
mohammad Naimi

Reputation: 2359

you should use $filter in aggregration

db.collection.aggregrate([
[
  {
    '$project': {
      'list': {
        '$filter': {
          'input': '$list', 
          'as': 'list1', 
          'cond': {
            '$eq': [
              '$$list1.employee_code', 1111
            ]
          }
        }
      }, 
      'user_id': 1
    }
  }
]
])

Upvotes: 2

Related Questions