Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find objects created in last week in MongoDB?
To find objects created in the last week in MongoDB, use the $gte operator with a date calculation that subtracts 7 days from the current date. This filters documents with dates greater than or equal to one week ago.
Syntax
db.collection.find({
"dateField": {
$gte: new Date(new Date() - 7 * 60 * 60 * 24 * 1000)
}
});
Sample Data
Let us first create a collection with documents to demonstrate the query ?
db.findObjectInLastWeekDemo.insertMany([
{"ShippingDate": new ISODate("2019-05-01")},
{"ShippingDate": new ISODate("2019-05-02")},
{"ShippingDate": new ISODate("2019-05-07")},
{"ShippingDate": new ISODate("2019-05-08")},
{"ShippingDate": new ISODate("2019-05-09")},
{"ShippingDate": new ISODate("2019-04-26")}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cda7dc4bf3115999ed511e0"),
ObjectId("5cda7dc4bf3115999ed511e1"),
ObjectId("5cda7dc4bf3115999ed511e2"),
ObjectId("5cda7dc4bf3115999ed511e3"),
ObjectId("5cda7dc4bf3115999ed511e4"),
ObjectId("5cda7dc4bf3115999ed511e5")
]
}
View All Documents
db.findObjectInLastWeekDemo.find().pretty();
{ "_id": ObjectId("5cda7dc4bf3115999ed511e0"), "ShippingDate": ISODate("2019-05-01T00:00:00Z") }
{ "_id": ObjectId("5cda7dc4bf3115999ed511e1"), "ShippingDate": ISODate("2019-05-02T00:00:00Z") }
{ "_id": ObjectId("5cda7dc4bf3115999ed511e2"), "ShippingDate": ISODate("2019-05-07T00:00:00Z") }
{ "_id": ObjectId("5cda7dc4bf3115999ed511e3"), "ShippingDate": ISODate("2019-05-08T00:00:00Z") }
{ "_id": ObjectId("5cda7dc4bf3115999ed511e4"), "ShippingDate": ISODate("2019-05-09T00:00:00Z") }
{ "_id": ObjectId("5cda7dc4bf3115999ed511e5"), "ShippingDate": ISODate("2019-04-26T00:00:00Z") }
Find Objects Created in Last Week
Here is the query to find objects created in the last week (assuming current date is 2019-05-14) ?
db.findObjectInLastWeekDemo.find({
ShippingDate: {
$gte: new Date(new Date() - 7 * 60 * 60 * 24 * 1000)
}
});
{ "_id": ObjectId("5cda7dc4bf3115999ed511e2"), "ShippingDate": ISODate("2019-05-07T00:00:00Z") }
{ "_id": ObjectId("5cda7dc4bf3115999ed511e3"), "ShippingDate": ISODate("2019-05-08T00:00:00Z") }
{ "_id": ObjectId("5cda7dc4bf3115999ed511e4"), "ShippingDate": ISODate("2019-05-09T00:00:00Z") }
How It Works
-
new Date()gets the current date and time -
7 * 60 * 60 * 24 * 1000calculates milliseconds in 7 days (7 days × 24 hours × 60 minutes × 60 seconds × 1000 milliseconds) -
$gtefinds documents with dates greater than or equal to the calculated past date
Conclusion
Use $gte with date arithmetic to filter documents by time ranges. The calculation new Date() - 7 * 60 * 60 * 24 * 1000 creates a timestamp exactly one week before the current moment.
Advertisements
