MongoDB was released in February 2009. It is an open-source document-oriented database and is classified as a NoSQL database. It follows the CAP theorem (Consistency Availability and Partition tolerance). It provides built-in support for the Sharding and replication. To ensure security MongoDB provides access control, authentication mechanism, and encryption.
MongoDB stores the records in a document in BSON format. It is an unstructured language and provides horizontal scalability and high-performance, data persistence. It follows the BASE ( Basically Available, Soft State, and Eventual Consistency )properties. It is used to handle big data faster than RDBMS.
In this article, we will learn about Query Modifiers in MongoDB along with the syntax and multiple Modifiers in MongoDB and so on.
Query Modifiers in MongoDB
Query modifiers are applied to queries to modify their behavior. Meta operators come under Query Modifiers. MongoDB supports different types of query operators while meta operators allow to change how a query result can appear.
They are used to shape the result, improve performance, and efficiently retrieve database documents. They are used in sorting, projection, limiting, and many more operations. They are also used to efficiently utilize the resource, increase the readability of the query, and make developers comfortable with the task.
Note: Most of the query modifiers are deprecated since v3.2 instead of query modifiers use cursor methods.
A list of Modifier Operator
- $comment is used to add a comment to the query. It is deprecated instead, comment() is used.
- $explain is used to report documents with an execution plan. It is deprecated instead, explain () is used.
- $hint is used to specify the index for a query. It is deprecated instead of it hint() is used.
- max() is used to specify the upper limit for the index of a query.
- min() and is used to specify a lower limit for the index of a query.
- $maxTimeMS is used to specify the maximum time in which the query should be executed.Time is specified in millisecond.
- $orderby is deprecated, sort is used instead of it. sort() carries out sorting of the documents in a specific order.
- $query is used to specify conditions to request a document.
- $returnKey is used to provide the index key from the result.
- $showDiskLoc is deprecated instead of it showRecordId() is used.
1. $comment in MongoDB
$comment is used to add a comment to the query. Comments are not stored in the database. If we want comments to be stored , add the comment as field and value in the document. $comment can be used as follows
Syntax:
db.collection.find( { condition }).comment( add_comment_related_to_condition )
or
db.collectionj.find( { condition } ,$comment : "comment" )
Example
Add a comment to the document which is not divisible by 3.
Query:
//collection used for example.
db.Digits.insertMany([{value:1},{value:12},{value:21},{value:27}]);
the db.Digits.find({ value: { $mod: [3, 1] } }).comment("Number not divisible by 3");
Output:
Explanation: find() method is used to request the document with a particular condition and $comment is used to provide details about the query .
2. $explain in MongoDB
$explain is used to report documents with an execution plan.
Syntax:
db.collection.find( { condition } ).explain(" executionStats") ;
Query:
GeeksforGeeks> db.Digits.find({ value: { $mod: [3, 1] } }).explain("executionStats");
Output contains various fields like explainVarsion, ,QueryPlanner,namespace,indexFilterSet and many more.
3. $hint in MongoDB
$hint is used to specify the index for a query. It is deprecated instead of it hint() is used.$text query cannot be used along with the hint() method. Initally indexes are to be created on the collection.createIndex() method is used to create an index.
Syntax:
db.collection.find().hint( { indexKey} )
Example: Use hint() in MongoDB
Query:
db.Digits.createIndex( {value:1});
db.Digits.find().hint({ value:1});
Output:
Explanation: Initially indexes are created on the collection using the createIndex() method.In the next query hint() method along with the find() method is used to get the result.
4. min() and max() in MongoDB
min() and max() are used to specify lower and upper limits respectively for the index in a query.
Syntax for min():
db.collection.find(condition).min( { field: lower limit }).hint( {index})
Syntax for max():
db.collection.find({condition}).max( { field: upper limit }).hint( index);
Example: Use min() and max() on Digits collection
Query:
db.Digits.find( { value : {$ gt :10}} ).min( { value:5}).hint( { value: 1});
db.Digits.find( { value : {$ lt :25}} ).max( { value:20}).hint( { value: 1});
Output:
Explanation:
- In the first query, Find() method is used to find the document with a value lesser than 25, and the max() method specifies the upper limit of 20 hence the documents below the upper limit that satisfy the condition are returned.
- In the second query, Find() method is used to find the document with value greater than 10 and min() method specify the lower limit to 5 hence the document above the lower limit that satisfy the condition are returned.
5. $maxTimeMS in MongoDB
$maxTimeMS is used to specify the maximum time in which the query should be executed. $maxTimeMS operator is deprecated instead of maxTimeMs() is used. Time is specified in millisecond with integral value and it should be in the range of [0 , 2147483647].
Syntax:
db.collection_name.find().maxTimeMs(mention maximum time);
Example : Use maxTimeMS() method
Query:
db.Digits.find().maxTimeMS(100);
Output:
Explanation: In the above example,Digits collections is used to store the documents.Documents are requested using find() and maxTimeMS() methods. maxTimeMS() is used to specify the maximum time in which the query should be executed.
6. $orderby in MongoDB
$orderby is deprecated, sort() method performs the same operation as $orderby. sort() carries out sorting of the documents in a specific order.Sort direction is specified by 1 and -1.1 for ascending order and -1 for descending.
Syntax:
For ascending order
db.collection_name.find().sort( {field: 1} );
for descending order
db.collection_name.find().sort( { field : -1})
Example: Use sort() method to sort the documents
Query:
db.Digits.find().sort({ values: -1} )
Output:
Explanation: The output contains the documents in the descending order.sort() method is used to sort the documents. As field is specified with -1 ,documents are displayed in descending order.
Conclusion
Query modifier are used to modify the query behaviour. They are used to shape the result, improve performance, and efficiently retrieve database documents. They are also used in sorting, projecting, limiting, and in many more operations. They are also used to efficiently utilize the resource, increase the readability of the query, and make developers comfortable with the task.By considering the syntax and advantages of the query modifers ,developers can use them to improve performance and functionality.