How to Find Objects Between Two Dates in MongoDB
- Query with Date Range in MongoDB
-
$gt
in MongoDB -
$gte
in MongoDB -
$lt
in MongoDB -
$lte
in MongoDB - Find Documents Between Two Dates in MongoDB
- Find Documents After Specific Date in MongoDB
- Find Documents Before Specific Date in MongoDB
- Comparison Based on Date in MongoDB
In this article, the problem of finding an object between two dates is discussed briefly. Moreover, operators $gte
, $lte
, $gt
, and $lt
used for this purpose are explained in brief detail.
Query with Date Range in MongoDB
This section will walk you through writing a MongoDB Date Range query to retrieve data based on a timestamp or a date range. Date queries in MongoDB, for example, are dates greater than or less than time or date.
To perform a query in MongoDB using a date range, use the basic syntax described below.
db.collection.find({
day: {
$gt: ISODate("2020-01-21"),
$lt: ISODate("2020-01-24")
}
})
All items in the collection whose day
field is more than or equal to 2020-01-21
but less than or equal to 2020-01-24
will be returned by this query. The steps outlined above are straightforward.
However, there are a few minor inconsistencies in these directions.
$gt
in MongoDB
Syntax:
{ field: { $gt: value } }
Because the field
value is greater than (i.e., >
) the specified value
, $gt
selects those documents.
For most data types, comparison operators only perform comparisons on fields when the BSON type matches the query value’s type. However, MongoDB’s type bracketing allows for limited cross-BSON comparison.
The examples below use the inventory
collection. This is the sample database that will be used below in all examples.
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 }
}
] )
Match Document Fields
Select all the documents in the inventory
collection where quantity
is greater than 20
.
db.inventory.find( { quantity: { $gt: 20 } } )
Output:
Perform the Update Based on Embedded Document Fields
The example below sets the price
field based on a $gt
comparison against a field in an embedded document.
db.inventory.updateOne(
{ "carrier.fee": { $gt: 2 } }, { $set: { "price": 9.99 } }
)
Output:
This updateOne()
function checks for a fee
subfield in an embedded document named carrier
. The first document finds a value for a fee
larger than 2 and sets the price: 9.99
.
To adjust the value of the price
field in all documents when the carrier.fee
is more than 2, use updateMany()
.
$gte
in MongoDB
Syntax:
{ field: { $gte: value } }
$gte
selects documents that have a field
value that is greater than or equal to (i.e. >=
) a given value (e.g. value
).
For most data types, comparison operators only perform comparisons on fields when the BSON type matches the query value’s type. However, MongoDB’s type bracketing allows for limited cross-BSON comparison.
Match Document Fields
Select all documents in the inventory
collection with a quantity greater than or equal to 20
.
db.inventory.find( { quantity: { $gte: 20 } } )
Output:
Perform the Update Based on Embedded Document Fields
The price
field is set using a $gte
comparison against a field in an embedded document in the following example.
db.inventory.updateMany(
{ "carrier.fee": { $gte: 2 } }, { $set: { "price": 9.99 } }
)
Output:
This updateOne()
function checks for a fee
subfield in an embedded document named carrier
. price: 9.99
is added to each document when fee
has a value more than or equal to 2.
Use updateOne()
to set the value of the price
field on just the first page when carrier.fee
is more than 2.
$lt
in MongoDB
Syntax:
{ field: { $lt: value } }
$lt
selects documents where the field
value is less than (or equal to) the specified value
.
For most data types, comparison operators only perform comparisons on fields when the BSON type matches the query value’s type. However, MongoDB’s type bracketing allows for limited cross-BSON comparison.
Match Document Fields
Select all documents in the inventory
collection with a quantity less than 20
.
db.inventory.find( { quantity: { $lt: 20 } } )
Output:
Perform the Update Based on Embedded Document Fields
The price
field will be set based on a $lt
comparison to a field in an embedded document in the following example.
db.inventory.updateMany( { "carrier.fee": { $lt: 20 } }, { $set: { price: 9.99 } } )
Output:
This updateOne()
function checks for a fee
subfield in an embedded document named carrier
. When the value of charge
is less than 2, it adds price: 9.99
to each record.
Use updateOne()
to set the value of the price
field on just the first page when carrier.fee
is less than 2.
$lte
in MongoDB
Syntax:
{ field: { $lte: value } }
$lte
selects documents with a field
value less than or equal to (i.e. =
) the specified value
.
For most data types, comparison operators only perform comparisons on fields when the BSON type matches the query value’s type. However, MongoDB’s type bracketing allows for limited cross-BSON comparison.
Match Document Fields
Consider the following example:
db.inventory.find( { quantity: { $lte: 20 } } )
This query selects all entries in the inventory
collection with a quantity field value of less than or equal to 20
.
Output:
Perform the Update Based on Embedded Document Fields
The price
field is set using a $lte
comparison against a field in an embedded document in the following example.
db.inventory.updateMany(
{ "carrier.fee": { $lte: 5 } }, { $set: { price: 9.99 } }
)
Output:
This updateMany()
function looks for a fee
subfield in an embedded document named carrier
. price: 9.99
is added to each document if fee
has a value less than or equal to 5.
When carrier.fee
is less than or equal to 5, use updateOne()
to alter the value of the price
field on only the first page.
The following information explains how to apply this syntax to a data collection using the accompanying 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 query below to find all documents having the day
field between two dates.
db.data.find({
day: {
$gt: ISODate("2020-01-21"),
$lt: ISODate("2020-01-24")
}
})
The query above 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 Specific Date in MongoDB
Use the query below to find all documents with the day
field set to a date after a specified date.
db.data.find({
day: {
$gt: ISODate("2020-01-22")
}
})
The query above 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 Specific Date in MongoDB
Use the query below to find all documents having the day
field set to before a specific date.
db.data.find({
day: {
$lt: ISODate("2020-01-22")
}
})
The query above 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 }
Comparison Based on Date in MongoDB
Let’s look at how to return a query depending on the date using MongoDB.
Create a collection called data
using the document to better grasp the idea. The following is the query to build a collection containing a record.
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 the find()
function, all of the documents in a collection will be selected. The following is the query for this.
db.data queryFromDate.find().pretty();
The query above will return the following documents, as shown in the screenshot below.
The following is the date-based return query. Records with a creation date after 2018-05-19T11:10:23Z
will be referred to 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 screenshot below.
So through the help of this article, the user came upon information about using the Date()
method. Examples briefly explain the $gte
and $lte
commands.
Moreover, return query based on data is also illustrated with code snippets.