MongoDB with date :
We have one collection with the below documents :
db.items.insertMany(
[{
name : "one",
date : new Date("2019-01-01")
},
{
name : "two",
date : new Date("2019-02-01")
},
{
name : "three",
date : new Date("2019-03-01")
},
{
name : "four",
date : new Date("2019-04-01")
},
{
name : "five",
date : new Date("2019-05-01")
},
{
name : "six",
date : new Date("2019-06-01")
},
{
name : "seven",
date : new Date("2019-07-01")
}]
)
Each document has two fields: name and date. In this post, I will show you how to find all the documents within two dates.
Comparison query operators :
We will use the below comparison query operators to fetch all data in a date range :
$gt : Greater than
$gte : Greater than or equal to
$lt : Less than
$lte : Less than or equal to
Find all documents greater than and less than two dates :
The below command will fetch all data greater than 2019-02-01 and less than 2019-06-01 :
db.items.find({
date : {
$gt : new Date("2019-02-01"),
$lt : new Date("2019-06-01")
}
})
It will return the below documents :
{ "_id" : ObjectId("5de54be2f6e59fd81d6ba8c9"), "name" : "three", "date" : ISODate("2019-03-01T00:00:00Z") }
{ "_id" : ObjectId("5de54be2f6e59fd81d6ba8ca"), "name" : "four", "date" : ISODate("2019-04-01T00:00:00Z") }
{ "_id" : ObjectId("5de54be2f6e59fd81d6ba8cb"), "name" : "five", "date" : ISODate("2019-05-01T00:00:00Z") }
Find all documents greater than equal to and less than equal to two dates :
We can also use $gte and $lte to get documents including the range. If we change the above example like below :
db.items.find({
date : {
$gte : new Date("2019-02-01"),
$lte : new Date("2019-06-01")
}
})
It will include both range documents :
{ "_id" : ObjectId("5de54be2f6e59fd81d6ba8c8"), "name" : "two", "date" : ISODate("2019-02-01T00:00:00Z") }
{ "_id" : ObjectId("5de54be2f6e59fd81d6ba8c9"), "name" : "three", "date" : ISODate("2019-03-01T00:00:00Z") }
{ "_id" : ObjectId("5de54be2f6e59fd81d6ba8ca"), "name" : "four", "date" : ISODate("2019-04-01T00:00:00Z") }
{ "_id" : ObjectId("5de54be2f6e59fd81d6ba8cb"), "name" : "five", "date" : ISODate("2019-05-01T00:00:00Z") }
{ "_id" : ObjectId("5de54be2f6e59fd81d6ba8cc"), "name" : "six", "date" : ISODate("2019-06-01T00:00:00Z") }