How to use element operators in MongoDB to filter data

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.

The $exists operator

The $exists operator enables the user to obtain documents from a collection regardless of whether a particular field is present or not.

Syntax

The syntax of $exists is:

{
field:
{
$exists: <boolean>
}
}

Return value

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.

Code example

Let's look at an example of $exists query:

//query
db.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 operator exists.

The $type operator

When 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 BSONBSON stands for Binary Javascript Object Notation. It is a binary-encoded representation of JSON documents. type.

Syntax

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.

Code example

Let's look at an example of $type query:

//query
db.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.

Run your queries

You can run all the previous MongoDB queries in the terminal below:

Terminal 1
Terminal
Loading...

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved