Reputation: 1978
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:
Upvotes: 2
Views: 1152
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
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