Array Operators: $elemMatch quiz

Hi Everyone,

db.surveys.find({results: {$elemMatch: {product :“abc”,score : 7}}}).count() >> this one shows correct output
db.surveys.find({results: {$elemMatch: {product :“abc”,score : “7”}}}).count() >> this returns worng output as score is of int type…

but how we can actually find out what is type of field as results differ if we choose wrong type for element value

Look into the $type operator. It can be used to filter fields by their type or to discover the data type of a field.

Hi @hunhale1991,

In addition to @007_jb,

You can also use the typeof operator in the mongo shell to find out the type of any specific field.

For instance, this is what you can do :

 var doc = db.surveys.findOne()

This will return one document from the surveys collection.

 typeof doc.<any field name present in the returned doc>

This will return the type of any specific field that you mention after the dot operator.

However, the best way to do this is to use Schema tab in the Compass. It provides more information.

Hope it helps!

If you have any other issue please feel free to get back to us.

Happy Learning :slight_smile:

Thanks,
Shubham Ranjan
Curriculum Support Engineer

@Shubham_Ranjan
Can you explain me please, why I got the correct output when I using db.surveys.find({results: {“product”: “abc”, score: 7}}).count() and I got SyntaxError: illegal character, when I using db.surveys.find({results: {$elemMatch: {product :“abc”,score : 7}}}).count() ?

I would first put all the fields names in quotes. I would also put $elemMatch in quotes.


It’s one of those funny quotes again

1 Like

Hi @Semion_79117,

As others have already mentioned please use straight quotes in your query.

Thanks,
Shubham Ranjan
Curriculum Services Engineer