JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Find objects between two dates in MongoDB

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

In this article, the problem of finding objects between two dates was briefly discussed. In addition, the operators $gte, $lte, $gt, and $lt used for this purpose were briefly explained in detail.


Querying date ranges in MongoDB

This section walks you through writing a MongoDB date range query to retrieve data based on a timestamp or date range. For example, a date query in MongoDB is a date that is greater than or less than a time or date.

To perform queries in MongoDB using date ranges, use the basic syntax described below.

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

This query will return all items in the collection where the date field is greater than or equal to 2020-01-21 but less than or equal to 2020-01-24. The steps outlined above are simple.

However, there are some minor inconsistencies in these directions.


$gt in MongoDB

grammar:

{ field: { $gt: value } }

Select those documents where the field value is greater than (or equal to >) the specified value .$gt

For most data types, comparison operators perform comparisons on fields only if the BSON type matches the type of the query value. However, MongoDB's type brackets allow limited cross-BSON comparisons.

The following examples use the Inventory collection. This is the sample database that will be used in all the examples below.

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 }
   }
] )

Matching document fields

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

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

Output:

Using the gt operator

Perform updates based on embedded document fields

$gtThe following example sets the price field based on a comparison with a field in an embedded document .

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

Output:

Using the gt operator 2

This updateOne()function checks the cost subfield in the embedded document named carrier. The first document finds a cost value greater than 2 and sets the price: 9.99.

To adjust the value of the price field in all documents when carrier.fee is greater than 2, use updateMany().


$gte in MongoDB

grammar:

{ field: { $gte: value } }

$gte selects >=documents where the field value is greater than or equal to (i.e.) a given value (e.g. value).

For most data types, comparison operators perform comparisons on fields only if the BSON type matches the type of the query value. However, MongoDB's type brackets allow limited cross-BSON comparisons.

Matching document fields

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

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

Output:

Using the gte operator

Perform updates based on embedded document fields

In the following example, the price field is set using $gte to compare with a field in the embedded document.

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

Output:

Using gte operator 2

This updateOne()function checks the fee subfield in the embedded document named carrier. price: When the value of fee is greater than or equal to 2, add 9.99 to each document.

When carrier.fee is greater than 2, use updateOne()to set the value of the price field only on the first page.


$lt in MongoDB

grammar:

{ field: { $lt: value } }

$ltSelects documents where the field value is less than (or equal to) the specified value.

For most data types, comparison operators perform comparisons on fields only if the BSON type matches the type of the query value. However, MongoDB's type brackets allow limited cross-BSON comparisons.

Matching document fields

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

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

Output:

Using the lt operator

Perform updates based on embedded document fields

In the following example, the price field is set based on a $lt comparison to a field in the embedded document.

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

Output:

Using the lt operator 2

This updateOne()function checks the charge subfield in the embedded document named carrier. When the charge value is less than 2, it adds price:9.99 to each record.

When carrier.fee is less than 2, use updateOne()to set the value of the price field only on the first page.


$lte in MongoDB

grammar:

{ field: { $lte: value } }

$lteSelects documents where the field value is less than or equal to (that is, =) the specified value.

For most data types, comparison operators perform comparisons on fields only if the BSON type matches the type of the query value. However, MongoDB's type brackets allow limited cross-BSON comparisons.

Matching document fields

Consider the following example:

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

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

Output:

Using the lte operator

Perform updates based on embedded document fields

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

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

Output:

Using lte operator 2

This updateMany()function looks for the fee subfield in the embedded document named carrier. price: If the value of fee is less than or equal to 5, 9.99 is added to each document.

When carrier.fee is less than or equal to 5, use updateOne()to change the value of the price field only on the first page.

The following information explains how to apply this syntax to a collection of data using the accompanying documentation.

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 query below to find all documents that have a date field between two dates.

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

The above query returns the following documents as shown below.

{ _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

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

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

The above query returns the following documents.

{ _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 date field is set before a specific date.

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

The above query returns the following documents.

{ _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 see how to use MongoDB to return queries based on dates.

Create a collection called data with the document to understand the idea better. Following is the query to build a collection containing records.

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")
}

Using find()the function, all the documents in the collection will be selected. Following is the query for this.

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

The above query will return the following documents as shown in the following screenshot.

Return query

Following is the return query based on date. Records created after 2018-05-19T11:10:23Z will be called as:

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

This query returns the following documents as shown in the following screenshot.

Return query 1

Hence, with the help of this article, the user got to know about Date()the method of using $gteand $ltecommands .

In addition, code snippets are used to illustrate queries based on the data returned.

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

Date comparison in MongoDB

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

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 querie

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

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial