This might be the silliest questions of all, but I can’t get it to work…
I am testing with the following to get the “name”:“goodBanana” object . I have tried a few filter options but looks like I am missing something fundamental…
So when you do a findOne, it returns the entire document, to get an element from an array you need to do the $unwind aggregation state. I added the document and did the aggregation with a match and limit to 1. Then it unwinds it into two documents, then matches those two documents for ‘goodBanana’
[
{
$match:
/**
* query: The query in MQL.
*/
{
"banana.name": "goodBanana",
},
},
{
$limit:
/**
* Provide the number of documents to limit.
*/
1,
},
{
$unwind:
/**
* path: Path to the array field.
* includeArrayIndex: Optional name for index.
* preserveNullAndEmptyArrays: Optional
* toggle to unwind null and empty values.
*/
{
path: "$banana",
},
},
{
$match:
/**
* query: The query in MQL.
*/
{
"banana.name": "goodBanana",
},
},
]
I found out about using $filtering the array in a $project. Good that you mentioned…
By the way, just started using MongoDB, so I am a newbie…
Tried $elemMatch for few hours today. it only returns the first array item that matches the condition. This is the problem… If you were to add to more bananas with the same values, $elemMatch still returns a single item. Do you know a way to do it with $elemMatch?