Comparison Operators
The comparison operators in MongoDB are used to perform value-based comparisons in queries.
The comparison operators in the MongoDB are shown as below:
Comparison Operator | Description | Syntax |
---|---|---|
$eq |
Matches values that are equal to a specified value. | { field: { $eq: value } } |
$ne |
Matches all values that are not equal to a specified value. | { field: { $ne: value } } |
$lt |
Matches values that are less than a specified value. | { field: { $lt: value } } |
$gt |
Matches values that are greater than a specified value. | { field: { $gt: value } } |
$lte |
Matches values that are less than or equal to a specified value. | { field: { $lte: value } } |
$gte |
Matches values that are greater than or equal to a specified value. | { field: { $gte: value } } |
$in |
Matches any of the values specified in an array. | { field: { $in: [<value1>, <value2>, ... ] } } |
Example of using $gte Operator
Let’s find out all those records in which the age of the person is equal to or greater than 23.
Query:
db.count_no,find( { "Age": {$gte:23} }, {"_id":0} );
Output:
Explanation: In the above image we have written a query to return the documents that have the age field greater than or equal to 23 and the id is not shown as we mentioned id:0
Example of Using $gt Operator
Let’s find out those people whose age is greater than 21.
Query:
db.count_no,find( { "Age": {$gt:21} }, {"_id":0} );
Output:
Explanation: In the above query we have used find() to retrieve the documents whose age is strictly greater than 21.
Example of Using $eq Operator
Let’s find out if the person named Krishna is present in our Collections or not.
Query:
db.count_no,find( { "name": {$eq:"Krishna"} }, {"_id":0} );
Output:
Explanation: In the above-mentioned query we used the $eq operator to find the document with the name Krishna.
MongoDB Query and Projection Operator
MongoDB query and projection operators allow users to control queries and results. Query operators help to filter data based on specific conditions. E.g., $eq,$and,$exists, etc.
Projection operators in MongoDB control which fields should be shown in the results. E.g., $project, $slice, $concat, etc.
In this article, we will learn about query and projection operators in MongoDB with detailed explanations and examples. Let’s start by learning the Query operators in MongoDB.