Operators are specialized symbols or keywords that mainly tell a compiler or interpreter how to perform logical or mathematical operations.
The element query operators are used to identify documents based on their fields. The current element operators are listed below:
$exists
$type
We use the following database to perform element operators where the database name is educative and has a collection named courses.
$exists
operatorThe $exists
operator enables the user to obtain documents from a collection regardless of whether a particular field is present or not.
The syntax of $exists
is:
{field:{$exists: <boolean>}}
When boolean is True
, $exists
matches the documents that have the field, including documents where the field value is null.
If it is false
, the query returns only the documents that do not have the field.
Let's look at an example of $exists
query:
//querydb.courses.find({"_id": {$exists: true,$gte: 11}}).pretty()//output[{ _id: 11, course_name: 'C++', hours: 15 },{ _id: 12, course_name: 'java', hours: 12 }]
The $exist
operator in the above example is returning only those values of id
that is greater or equal to 11.
Note: MongoDB
$exists
does not work the same as SQL operatorexists
.
$type
operatorWhen we work with unstructured data where data types are unpredictable, the $type
operator picks the documents where the field value is an instance of the provided numeric
The syntax of the $type
query for a single BSON type is:
{field:{$type: <BSON type>}}
The syntax of the $type
query for an array of BSON types is:
{field:{$type: [ <BSON type1> , <BSON type2>, ... ]}}
It returns documents in which the BSON type of the field is the same as the BSON type given to the $type
.
Let's look at an example of $type
query:
//querydb.courses.find({"course_name": {$type: "string"}})//output[{ _id: 10, course_name: 'python', hours: 10 },{ _id: 11, course_name: 'C++', hours: 15 },{ _id: 12, course_name: 'java', hours: 12 }]
The $type
operator in the above example returns only those values of course_name
that is a string.
You can run all the previous MongoDB queries in the terminal below:
Free Resources