TL;DR: MongoDB provides a $type operator that can be helpful when you need to select documents where the value of the fields is of a certain type. This can be really helpful, but when it comes to selecting array values, things can get a bit tricky. It is best to use some form of workaround to get the selection you need in such cases.
What is the $type Operator?
The $type operator allows you to make your query selection more specific by selecting only documents that have a field containing a value that is a certain data type. Suppose you had a collection like this:
If you want to get only the documents where the “name” field contains a string value, you could use the following query:
Since 2 is the code for a string data type, the query will only return the second document: the one with the string “George” in the “name” field. Since the first document has an object type, it won’t be returned.
MongoDB offers codes for a number of data types, as shown in the chart below:
Oddities with Arrays
While the $type operator generally works as expected, determining whether a field contains an array can be a bit tricky. This is because when you are dealing with an array field, the $type operator checks the type against the array elements themselves instead of the field. This means that for an array field, it will only return documents where the array contains another array.
This is helpful if you are looking for multidimensional arrays, but does not help the case where you need to know if the field itself is an array, which was possible when looking for a string value. Finding out if the field is an array will require a workaround.
How to Find a Field of Type Array
This will do the trick, but it does come with a substantial performance decrease when running the query.
A workaround that avoids this is to use $elemMatch to check for the existence of an array, like this:
This will do the trick, except in the case where you need to also include empty arrays. To do this, you can add a sort that will allow empty arrays to be returned as well:
How to Get MongoDB
MongDB is well-suited for numerous applications, especially in cases of big data that needs to be queried quickly. One way to easily set up a MongoDB database is to have it remotely hosted as a service in the cloud.
One company that offers this is Morpheus, where you can get MongoDB (and several other databases) as a service in the cloud. With easy setup and replication, and running on a high performance infrastructure with Solid State Drives, why not look open a free account today!