How should i get the id of the matched object from a array?
Currently i am getting all the ids from pricing array.
While i just want the one that matched.
Code –
await Item.find(
{_id: "663a4dbb97674691089c835a", pricing: {$elemMatch: {mrp: 100, price: 100}}},
{"pricing._id": 1})
MongoDB Document –
{
"_id": {
"$oid": "663a4dbb97674691089c835a"
},
"desc": {
"name": "BLA BLA",
},
"pricing": [
{
"firstAddedDate": "05/30/2024",
"mrp": 100,
"price": 100,
"qty": 1,
"_id": {
"$oid": "66578e181df0f2a544263b2b"
}
},
{
"firstAddedDate": "05/30/2024",
"mrp": 100,
"price": 80,
"qty": -1,
"_id": {
"$oid": "66580f3425b849794bb87bd7"
}
}
]
}
Result I want –
66578e181df0f2a544263b2b
2
Answers
Use the
$
projection operator:https://www.mongodb.com/docs/manual/reference/operator/projection/positional/
Project
pricing.$._id
Approach 1
In the projection, you should use
$filter
operator to filter the matching element.Demo Approach 1 @ Mongo Playground
Approach 2
You may work with
$map
to return the matched_id
.Demo Approach 2 @ Mongo Playground
Approach 3
Work with
pricing.$
to return first matching element.Demo Approach 3 @ Mongo Playground