Greetings,
I’m getting some confusing results when using $elemMatch and the " { } " . Hoping someone can shed some light.
Here is a typical $elemMatch search:
db.survey.find( { results: { $elemMatch : { product: ‘abc’ }}})
I found out that we can add "{ } " like so to return only shows selected fields like a projection:
db.survey.find( {}, { results: { $elemMatch : { product: ‘abc’ }}, _id:1, results:0})
The odd thing happens when I remove the " { } ", and it doesn’t return any documents:
db.survey.find( { results: { $elemMatch : { product: ‘abc’ }}, _id:1, results:0})
Thanks!
Below are the records in the survey collection:
db.survey.insertMany( [
{ “_id”: 1, “results”: [ { “product”: “abc”, “score”: 10 },
{ “product”: “xyz”, “score”: 5 } ] },
{ “_id”: 2, “results”: [ { “product”: “abc”, “score”: 8 },
{ “product”: “xyz”, “score”: 7 } ] },
{ “_id”: 3, “results”: [ {product: “abc” , “score”:7},
{ “product”: “xyz”, “score”: 8 } ] },
{ “_id”: 4, “results”: [product: “abc” , “score”:7 },
{ “product”: “def”, “score”: 8 } ] },
{ “_id”: 5, “results”: [ { “product”: “abc”},
{ “product”: “def”} ] }
] )