JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Date comparison in MongoDB

Author:JIYIK Last Updated:2025/04/28 Views:

This MongoDB tutorial discusses the issue of returning Date-based queries. In addition, there is also a good tutorial on how to use Date Range queries in MongoDB.


Using date ranges in MongoDB

We will learn to write MongoDB date range queries to fetch records based on a timestamp or date range. For example, a MongoDB date greater than or less than a time or date is an example of a date query.

To run a query with a date range in MongoDB, use the following basic syntax.

db.collection.find({
    day: {
        $gt: ISODate("2020-01-21"),
        $lt: ISODate("2020-01-24")
    }
})

This query returns all records in the collection where the Day field is greater than or equal to 2020-01-21 but less than or equal to 2020-01-24.


Using $gt in MongoDB

grammar:

{ field: { $gt: value } }

The value of the field is greater than (that is >) the supplied value; therefore, $gt selects those documents. Comparison operators perform comparisons on fields only if the BSON type matches the query value type for most data types.

Type brackets in MongoDB allow limited cross-BSON comparisons. The following example uses the Inventory collection.

db.inventory.insertMany( [
   {
      "item": "nuts", "quantity": 31,
      "carrier": { "name": "import", "fee": 3 }
   },
   {
      "item": "screws", "quantity": 50,
      "carrier": { "name": "import", "fee": 4 }
   },
   {
      "item": "washers", "quantity": 11,
      "carrier": { "name": "import", "fee": 1 }
   }
] )

Selects all documents in the inventory collection where the quantity is greater than 20.

db.inventory.find( { quantity: { $gt: 20 } } )

Output:

Using $gt in MongoDB

The following example sets the price field based on a comparison of $gt to a field in the embedded document.

db.inventory.updateOne(
   { "carrier.fee": { $gt: 2 } }, { $set: { "price": 9.99 } }
)

Output:

Perform updates based on embedded document fields

This updateOne()method looks for an embedded document named carrier that contains a fee subfield. The first document it finds has a fee value greater than 2; it sets the price to: 9.99.

Use updateMany()to change the value of the price field in all documents where carrier.fee is greater than 2.


Using $gte in MongoDB

grammar:

{ field: { $gte: value } }

$gteSelects >=documents where the field value is greater than or equal to (i.e.) a provided value (e.g. value). The following example uses the inventory collection.

db.inventory.insertMany( [
   {
      "item": "nuts", "quantity": 31,
      "carrier": { "name": "import", "fee": 3 }
   },
   {
      "item": "bolts", "quantity": 51,
      "carrier": { "name": "import", "fee": 4 }
   },
   {
      "item": "washers", "quantity": 11,
      "carrier": { "name": "import", "fee": 1 }
   }
] )

All documents in the inventory collection with a quantity greater than or equal to 20 should be selected.

db.inventory.find( { quantity: { $gte: 20 } } )

Output:

Using $gte in MongoDB

The price field is set in the following example and compared to a field in the embedded document using $gte.

db.inventory.updateMany(
   { "carrier.fee": { $gte: 2 } }, { $set: { "price": 9.99 } }
)

Output:

Using $gte to perform updates based on embedded document fields


Using $lt in MongoDB

syntax:

{ field: { $lt: value } }

$ltSelects documents where the field value is less than (that is) the provided value. The following example uses the previous inventory collection.

Selects all documents in the inventory collection that have a quantity less than 20.

db.inventory.find( { quantity: { $lt: 20 } } )

Output:

Using $lt in MongoDB

The next example sets the price field based on a $lt comparison to a field in an embedded document.

db.inventory.updateMany( { "carrier.fee": { $lt: 20 } }, { $set: { price: 9.99 } } )

Output:

Using $lt to perform updates based on embedded document fields


Using $lte in MongoDB

syntax:

{ field: { $lte: value } }

$lteSelects =documents where the field value is less than or equal to (that is) the provided value. The following example uses the previous inventory collection.

Consider the following example.

db.inventory.find( { quantity: { $lte: 20 } } )

This query returns all entries in the Inventory collection that have a Quantity field value less than or equal to 20.

Output:

Using $lte in MongoDB

The price field is set in the following example, using $lte to compare to a field in the embedded document.

db.inventory.updateMany(
   { "carrier.fee": { $lte: 5 } }, { $set: { price: 9.99 } }
)

Output:

Perform updates based on embedded document fields using $lte

The information below demonstrates how to apply this syntax to a dataset using the following documents.

db.data.insertOne({day: new Date("2022-01-20"), amount: 40})
db.data.insertOne({day: new Date("2022-01-21"), amount: 32})
db.data.insertOne({day: new Date("2022-01-22"), amount: 19})
db.data.insertOne({day: new Date("2022-01-23"), amount: 29})
db.data.insertOne({day: new Date("2022-01-24"), amount: 35})

Find documents between two dates in MongoDB

Use the following query to discover all documents that have the "day" field between two dates.

db.data.find({
    day: {
        $gt: ISODate("2020-01-21"),
        $lt: ISODate("2020-01-24")
    }
})

Output:

{ _id: ObjectId("618548bc7529c93ea0b41490"),
  day: 2020-01-22T00:00:00.000Z,
  amount: 19 }

{ _id: ObjectId("618548bc7529c93ea0b41491"),
  day: 2020-01-23T00:00:00.000Z,
  amount: 29 }

Find documents after a specific date in MongoDB

To find all documents where the Day field is set to a date after a specific date, use the following query.

db.data.find({
    day: {
        $gt: ISODate("2020-01-22")
    }
})

Output:

{ _id: ObjectId("618548bc7529c93ea0b41491"),
  day: 2020-01-23T00:00:00.000Z,
  amount: 29 }

{ _id: ObjectId("618548bc7529c93ea0b41492"),
  day: 2020-01-24T00:00:00.000Z,
  amount: 35 }

Find documents before a specific date in MongoDB

Use the following query to find all documents where the Days field is set before a specified date.

db.data.find({
    day: {
        $lt: ISODate("2020-01-22")
    }
})

Output:

{ _id: ObjectId("618548bc7529c93ea0b4148e"),
  day: 2020-01-20T00:00:00.000Z,
  amount: 40 }

{ _id: ObjectId("618548bc7529c93ea0b4148f"),
  day: 2020-01-21T00:00:00.000Z,
  amount: 32 }

Date based comparison in MongoDB

Let's use MongoDB to return a date-based query. First, create a collection called "data" with a document to further understand the concept.

db.data.insertOne({"PassengerName":"John","PassengerAge":23,"PassengerArrivalTime":new ISODate("2018-03-10 14:45:56")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a57be9064dcd4a68b70e4")
}
db.data.insertOne({"PassengerName":"Larry","PassengerAge":21,"PassengerArrivalTime":new ISODate("2018-05-19 11:10:23")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e5")
}
db.data.insertOne({"PassengerName":"Mike","PassengerAge":24,"PassengerArrivalTime":new ISODate("2018-08-25 16:40:12")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e6")
}
db.data.insertOne({"PassengerName":"Carol","PassengerAge":26,"PassengerArrivalTime":new ISODate("2019-01-29 09:45:10")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e7")
}

Use find()the function to display all documents in a collection.

db.data queryFromDate.find().pretty();

Output:

Use the find() function to return all documents in a collection.

Following is the return query based on date. Records with creation date after 2018-05-19T11:10:23Z will be returned.

> db.data queryFromDate.find({"PassengerArrivalTime" : { $gte : new ISODate("2018-05-19T11:10:23Z") }}).pretty();

Output:

Return documents from a collection using a date-based query

In this article, we have learned how to use Date()the method. The example briefly explains the $gte and $lte commands and the query based on the returned data.

Previous:Composite Indexes in MongoDB

Next: None

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Composite Indexes in MongoDB

Publish Date:2025/04/28 Views:151 Category:MongoDB

Sometimes we need to create an index that contains multiple fields. For example, if your document contains a field called Sex, it may contain two other fields, such as Male and Female. These fields may have values ​​like Yes or No. In t

$unset operator in MongoDB

Publish Date:2025/04/27 Views:78 Category:MongoDB

This article will discuss how the $unset operator works in MongoDB. Additionally, we will demonstrate the use of this operator to remove a field from all documents in a MongoDB collection. $unset operator in MongoDB $unset is an operator us

Compass Filters in MongoDB

Publish Date:2025/04/27 Views:133 Category:MongoDB

This short article will cover the various ways to use Compass filters in MongoDB . Compass Filters in MongoDB MongoDB has a GUI called Compass . It is also known as MongoDB GUI. Users can use MongoDB to inspect the contents of their stored

Sorting by timestamp in MongoDB

Publish Date:2025/04/27 Views:54 Category:MongoDB

This article will introduce various methods of sorting timestamps in MongoDB. Sorting by timestamp in MongoDB sort() The method will sort documents in MongoDB. The method accepts a document containing a list of fields and the order in which

Deleting a user from a database in MongoDB

Publish Date:2025/04/27 Views:51 Category:MongoDB

This article will explain how to delete a user from a MongoDB database. In addition, we will see an example to make the topic easier to understand. Deleting a User from a MongoDB Database Sometimes we need to remove a particular user from t

Deleting items by ID in MongoDB

Publish Date:2025/04/27 Views:159 Category:MongoDB

Sometimes we need to delete data from a database based on specified criteria. Unlike other SQL databases, MongoDB does not include SQL queries for this purpose. Instead, it uses commands. This article will discuss how to delete documents ba

Using ISODate for date queries in MongoDB

Publish Date:2025/04/27 Views:77 Category:MongoDB

This MongoDB tutorial article will explain Date() the methods. This article introduces different ways to query using dates. Date() Method in MongoDB Date() The method returns the date as a string or a Date object. In the MongoDB shell or mo

Return unique values in MongoDB

Publish Date:2025/04/27 Views:191 Category:MongoDB

In this article, we will address how to use the MongoDB distinct() method to return unique values. In addition, returning unique values ​​in arrays and fields is discussed. In MongoDB, sometimes you may want to present or return unique

Querying documents with array size greater than 1 in MongoDB

Publish Date:2025/04/27 Views:154 Category:MongoDB

When working with projects where you need to validate the size of an array or find elements whose size is greater or less than a certain length, you might use MongoDB operators such as $size, $where, $exists, etc. The methods discussed belo

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial