MongoDB Comparison Operator Examples
Let’s look at the examples of comparison operators. We will cover each comparison operator in MongoDB.
In the following examples, we are working with:
Database: w3wiki
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.
Using $nin
operator:
In this example, we are retrieving only those employee’s documents whose name is not Amit or Suman.
Query:
db.contributor.find({name: {$nin: ["Amit", "Suman"]}}).pretty()
Output
Using $in
operator
In this example, we are retrieving only those employee’s documents whose name is either Amit or Suman.
Query:
db.contributor.find({name: {$in: ["Amit", "Suman"]}}).pretty()
Output:
Using $lt
operator
In this example, we are selecting those documents where the value of the salary field is less than 2000.
Query:
db.contributor.find({salary: {$lt: 2000}}).pretty()
Output:
Using $eq
operator
In this example, we are selecting those documents where the value of the branch field is equal to CSE.
Query:
db.contributor.find({branch: {$eq: "CSE"}}).pretty()
Output:
Using $ne
operator
In this example, we are selecting those documents where the value of the branch field is not equal to CSE.
Query:
db.contributor.find({branch: {$ne: "CSE"}}).pretty()
Output:
MongoDB – Comparison Query Operators
Comparison Query Operators in MongoDB are used to filter documents based on some specific criteria within their fields.
MongoDB uses various comparison query operators to compare the values of the documents. The following table contains the comparison query operators:
Operators | Description |
---|---|
$eq | Matches the values of the fields that are equal to a specified value. |
$ne | Matches all values of the field that are not equal to a specified value. |
$gt | Matches values of the fields that are greater than a specified value. |
$gte | Matches values of the fields that are greater than equal to the specified value. |
$lt | Matches values of the fields that are less than a specified value |
$lte | Matches values of the fields that are less than equal to the specified value |
$in | Matches any of the values specified in an array. |
$nin | Matches none of the values specified in an array. |
Contact Us