How to Compare Dates in MongoDB

MD Aminul Islam Feb 02, 2024
How to Compare Dates in MongoDB

The date is a common field in most databases, and sometimes we need to find an exact document from a collection in MongoDB. For example, if we have a collection of orders, we may search for these documents before or after a specific date.

In this article, we will see how we can compare dates in MongoDB. Also, we will see a relevant example with an explanation to make the topic easier.

Compare Dates in MongoDB

For finding any specific document in a collection, we have to use the built-in method in MongoDB named find(). This method will pass our specified criteria to retrieve specific documents.

Then, we will use the ISODate() method to select a date.

In our example below, we will see how we can compare two fields in MongoDB. First, let’s insert some documents into our collection.

db.order.insertMany( [
   { _id: 0, type: "Product A", OrderDate: new ISODate("2021-05-18T14:11:30Z") },
   { _id: 1, type: "Product B", OrderDate: new ISODate("2020-03-20T11:31:05Z") },
   { _id: 2, type: "Product C", OrderDate: new ISODate("2020-01-15T06:32:15Z") }
] )

Now let’s retrieve only these data that were placed after the date 2021-02-22T10:03:46.000Z. The command for this will be as follows.

db.order.find( { OrderDate: { $gt: ISODate("2021-02-22T10:03:46.000Z") } } )

In the above command, $gt is a comparison operator (Greater Than). There are some other comparison operators that you can use when necessary.

Available Comparison Operators in MongoDB

Below shared the available comparison operator that can be used with aggregation in MongoDB.

  • $eq - This represents the Equal operator.
  • $ne - This represents the Not Equal operator.
  • $gt - This represents the Greater Than operator.
  • $gte - This represents the Greater Than or Equal operator.
  • $lt - This represents the Less Than operator.
  • $lte - This represents the Less Than or Equal operator.
  • $in - This matches any values in an array.
  • $nin - This matches none of the values in an array.

Now, after executing the above command, you will get the below-resulting output in your console:

{ _id: 0,
  type: 'Product A',
  OrderDate: 2021-05-18T14:11:30.000Z }

Note: Please check if you are in the right collection. To switch on a specific collection, use the command use YourDB; otherwise, it will give you an error.

Please note that the commands in this article are for the MongoDB database and must be run on the MongoDB console.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - MongoDB Date