I'm working on retrieving selective data from an array based on certain conditions. But I don't to unwind it. Is there any way in mongoDB to project a single element in array of objects which matches a condition.
Asked
Active
Viewed 33 times
2
-
[You can filter the array](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter/) – mousetail Jul 21 '22 at 07:40
-
Can you add more details to your question, which specific element from array you want to select? – turivishal Jul 21 '22 at 07:41
-
Your question s already answered at the following post. Also, note that there are different ways of achieving the result: [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection). – prasad_ Jul 21 '22 at 11:08
1 Answers
0
The positional operator $ would be perfect here, from the docs:
The positional $ operator limits the contents of an to return the first element that matches the query condition on the array.
For input in the structure:
[
{
"arr": [
{
value: "other value"
},
{
value: "match this"
},
{
value: "dont match"
}
]
}
]
You just use this query:
db.collection.find({
"arr.value": "match this"
},
{
"arr.$": 1
})
Output:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"arr": [
{
"value": "match this"
}
]
}
]

Tom Slabbaert
- 21,288
- 10
- 30
- 43