Find objects created in last week in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use Date() along with $gte operator to find objects created last week. Here the curdate is as follows in my system −

> new Date();
ISODate("2019-05-14T08:32:42.773Z")

Let us first create a collection with documents −

> db.findObectInLastWeekDemo.insertOne({"ShippingDate":new ISODate("2019-05-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda7dc4bf3115999ed511e0")
}
> db.findObectInLastWeekDemo.insertOne({"ShippingDate":new ISODate("2019-05-02")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda7dc4bf3115999ed511e1")
}
> db.findObectInLastWeekDemo.insertOne({"ShippingDate":new ISODate("2019-05-08")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda7dc4bf3115999ed511e2")
}
> db.findObectInLastWeekDemo.insertOne({"ShippingDate":new ISODate("2019-05-07")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda7dc4bf3115999ed511e3")
}
> db.findObectInLastWeekDemo.insertOne({"ShippingDate":new ISODate("2019-05-09")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda7dc4bf3115999ed511e4")
}
> db.findObectInLastWeekDemo.insertOne({"ShippingDate":new ISODate("2019-04-26")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda7dc4bf3115999ed511e5")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.findObectInLastWeekDemo.find().pretty();

This will produce the following output −

{ "_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-08T00:00:00Z") }
{ "_id" : ObjectId("5cda7dc4bf3115999ed511e3"), "ShippingDate" : ISODate("2019-05-07T00:00:00Z") }
{ "_id" : ObjectId("5cda7dc4bf3115999ed511e4"), "ShippingDate" : ISODate("2019-05-09T00:00:00Z") }
{ "_id" : ObjectId("5cda7dc4bf3115999ed511e5"), "ShippingDate" : ISODate("2019-04-26T00:00:00Z") }

Here is the query to find objects created in last week in MongoDB −

> db.findObectInLastWeekDemo.find({ShippingDate:{$gte: new Date(new Date() - 7 * 60 * 60 * 24 * 1000)}});

This will produce the following output −

{ "_id" : ObjectId("5cda7dc4bf3115999ed511e2"), "ShippingDate" : ISODate("2019-05-08T00:00:00Z") }
{ "_id" : ObjectId("5cda7dc4bf3115999ed511e4"), "ShippingDate" : ISODate("2019-05-09T00:00:00Z") }
raja
Published on 22-May-2019 11:08:14
Advertisements