"{ } " usage when finding elements in array

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”} ] }
] )

That is not odd, that is the way it works, that is the way it is documented. If you look at the documentation, you will see that find() is a method (or a class function if you prefer) that takes some parameters. The first one is a query. When you remove {}, the { results : ... } part becomes the query rather than an optional parameter.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.