How to use miscellaneous operators in MongoDB to filter data

Document-oriented database, MongoDB, is a type of NoSQL database. Different types of operators are available in MongoDB for usage when interacting with the database. In this Answer, will learn about miscellaneous operators in MongoDB.

Miscellaneous operators are a combination of different operators. These operators are mostly used to perform mathematical functions in MongoDB.

Let's discuss these three miscellaneous operators:

  • $comment

  • $rand

  • $natural

We use the following database to perform different logical operators where the database name is educative, and it has a collection named courses:

The $commentoperator

The $comment operator is used to add some comments to the query. It helps the reader understand what the query is doing. As it shows a profile log, it becomes easy for us to interpret the data.

Syntax

The syntax of the $comment operator is as follows:

db.collection.find(
{
<query>, $comment: <comment>
}
)

Example

Here's an example of $comment operator:

//query
db.courses.find(
{
hours: { $mod: [ 2, 0 ] },
$comment: "Find even values of hours."
}
)
//output
[
{ _id: 10, course_name: 'python', hours: 10 },
{ _id: 12, course_name: 'java', hours: 12 },
{ _id: 13, course_name: 'javascript', hours: 12 }
]

The $randoperator

The $rand operator returns a random float number between 1 and 0. We can also generate random numbers within the given range by using the $rand operator.

Syntax

The syntax of the the $rand operator is as follows:

{
$rand: {}
}

Example

Here's an example of the $rand operator:

//query
db.courses.find({ hours: 12, $expr: {rand: {} } })
//output
[
{ _id: 12, course_name: 'java', hours: 12 },
{ _id: 13, course_name: 'javascript', hours: 12 }
]

The $naturaloperator

The $natural operator scans the collection in either a forward or backward direction. 1 is used for forward, and -1 is used for reverse traversal. It can be used in the conjunction with the hint() method to return documents in the natural order.

Example

Here's an example of the $natural operator:

//query
db.courses.find().hint( { $natural : -1 } )
//output
[
{ _id: 13, course_name: 'javascript', hours: 12 },
{ _id: 12, course_name: 'java', hours: 12 },
{ _id: 11, course_name: 'C++', hours: 15 },
{ _id: 10, course_name: 'python', hours: 10 }
]

Terminal

We can run all the aforementioned MongoDB queries in the terminal below:

Terminal 1
Terminal
Loading...

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved