Comparison Query Operator in MongoDB

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

When you’re working with data stored in MongoDB, there may be times when you need to compare two expressions to determine whether one is greater than, less than or equal to another. We can use comparison query operators to evaluate expressions and obtain the information we need. In this article, we’ll explain how to use comparison query operator in MongoDB and provide some examples of their use.

Prerequisite

Before moving forward with this tutorial, be sure that you have MongoDB installed and configured on your machine.

Examples of Comparison Query Operators

In this tutorial, we’ll show you how to make use of the various comparison query operators that are available in MongoDB. We’ll need to create a sample dataset that we can use in our examples.

Let’s start by logging in to our Mongo shell. We’ll execute the commands shown below:

  • First, we create the database.
1
use inventory
  • Then, we insert documents into the stock collection. If this collection doesn’t yet exist, it will be created upon insertion of the documents.
1
2
3
4
5
6
7
db.stock.insertMany( [
    { _id: 1001, item: { name: "p1", code: "525" }, qty: 32, tags: [ "x", "y", "z" ] },
    { _id: 1002, item: { name: "p2", code: "526" }, qty: 45, tags: [ "y" ] },
    { _id: 1003, item: { name: "p3", code: "527" }, qty: 21, tags: [ "x", "y" ] },
    { _id: 1004, item: { name: "p4", code: "528" }, qty: 90, tags: [ "y", "x" ] },
    { _id: 1005, item: { name: "p5", code: "529" }, qty: 25, tags: [ [ "x", "y" ], "z" ] }
] );

After the insert operations are complete, we should have a collection containing the following documents:

1
2
3
4
5
{ "_id" : 1001, "item" : { "name" : "p1", "code" : "525" }, "qty" : 32, "tags" : [ "x", "y", "z" ] }
{ "_id" : 1002, "item" : { "name" : "p2", "code" : "526" }, "qty" : 45, "tags" : [ "y" ] }
{ "_id" : 1003, "item" : { "name" : "p3", "code" : "527" }, "qty" : 21, "tags" : [ "x", "y" ] }
{ "_id" : 1004, "item" : { "name" : "p4", "code" : "528" }, "qty" : 90, "tags" : [ "y", "x" ] }
{ "_id" : 1005, "item" : { "name" : "p5", "code" : "529" }, "qty" : 25, "tags" : [ [ "x", "y" ], "z" ] }

In MongoDB, comparison query operators compare two value expressions and then retrieve the documents that match the conditions in which the operators are used. Shown below are the conditional operators that we’ll be using in this tutorial. Let’s take a look at how each one works:

  • $eq – This operator retrieves documents from a collection that are equal to the defined expression.
  • $gte – This operator retrieves documents from a collection that are greater than or equal to the defined value of a expression.
  • $lte – This operator retrieves documents from a collection that are less than or equal to the defined value of expression.
  • $lt – This operator retrieves documents from a collection that are less than the given expression.

$eq Operator

As we mentioned in the previous section, the $eq operator fetches documents where its field values are equal to the defined expression. Shown below is the basic form of the $eq syntax as it’s used in a query:

1
> db.<dbCollection>.find( {<the_field_name> : {$eq : [<Value>]}} )

Let’s take a closer look at this query syntax:

  • ‘the_field_name’ – This represents the name of the field we wish to retrieve within the document.
  • ‘Value’ – This represents the defined condition that needs to be matched against the specified field.
1
> db.stock.find( { qty: { $eq: 45 } } ).pretty();

The command shown above will be retrieving documents from the ‘stock’ collection where the value of ‘qty’ equals the given value; in this case, the value is 45.

NOTE: the pretty() command displays the result in a more readable format.

The output should look something like this:

1
2
3
4
5
6
7
8
9
10
11
{
        "_id" : 1002,
        "item" : {
                "name" : "p2",
                "code" : "526"
        },
        "qty" : 45,
        "tags" : [
                "y"
        ]
}

$gt Operator

The $gt operator retrieves documents that contain fields having values greater than the specified value.

The basic syntax is as follows:

1
> db.<dbCollection>.find( {<the_field_name> : {$gt : [<Value>]}} )

Let’s try an example using this operator:

1
db.stock.find( { qty: { $gt: 25 } } );

The output should look something like the following:

1
2
3
{ "_id" : 1001, "item" : { "name" : "p1", "code" : "525" }, "qty" : 32, "tags" : [ "x", "y", "z" ] }
{ "_id" : 1002, "item" : { "name" : "p2", "code" : "526" }, "qty" : 45, "tags" : [ "y" ] }
{ "_id" : 1004, "item" : { "name" : "p4", "code" : "528" }, "qty" : 90, "tags" : [ "y", "x" ] }

Conclusion

Comparison query operators make it easy to compare expressions in MongoDB queries and retrieve just the records that match your conditions. In this article, we explained how to use comparison query operators in MongoDB and looked at some examples of queries containing the most common operators. With these examples to guide you, you’ll be able to make use of comparison query operators in your own MongoDB queries.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.