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
:
$comment
operatorThe $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.
The syntax of the $comment
operator is as follows:
db.collection.find({<query>, $comment: <comment>})
Here's an example of $comment
operator:
//querydb.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 }]
$rand
operatorThe $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.
The syntax of the the $rand
operator is as follows:
{$rand: {}}
Here's an example of the $rand
operator:
//querydb.courses.find({ hours: 12, $expr: {rand: {} } })//output[{ _id: 12, course_name: 'java', hours: 12 },{ _id: 13, course_name: 'javascript', hours: 12 }]
$natural
operatorThe $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.
Here's an example of the $natural
operator:
//querydb.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 }]
We can run all the aforementioned MongoDB queries in the terminal below:
Free Resources