Getting MongoDB results from the previous month

MongoDBDatabaseBig Data Analytics

At first, get the current month and subtract by 1 to fetch previous month records. Let us first create a collection with documents −

> db.findOneMonthAgoData.insertOne({"CustomerName":"Chris","PurchaseDate":new ISODate("2019-12-26")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e04e16c150ee0e76c06a04f")
}
> db.findOneMonthAgoData.insertOne({"CustomerName":"David","PurchaseDate":new ISODate("2019-11-26")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e04e178150ee0e76c06a050")
}
> db.findOneMonthAgoData.insertOne({"CustomerName":"Bob","PurchaseDate":new ISODate("2020-11-26")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e04e186150ee0e76c06a051")
}

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

> db.findOneMonthAgoData.find();

This will produce the following output −

{ "_id" : ObjectId("5e04e16c150ee0e76c06a04f"), "CustomerName" : "Chris", "PurchaseDate" : ISODate("2019-12-26T00:00:00Z") }
{ "_id" : ObjectId("5e04e178150ee0e76c06a050"), "CustomerName" : "David", "PurchaseDate" : ISODate("2019-11-26T00:00:00Z") }
{ "_id" : ObjectId("5e04e186150ee0e76c06a051"), "CustomerName" : "Bob", "PurchaseDate" : ISODate("2020-11-26T00:00:00Z") }

Here is the query to get result from previous month −

> monthData=new Date();
ISODate("2019-12-26T16:43:04.283Z")
> monthData.setMonth(monthData.getMonth() - 1);
1574786584283
> db.findOneMonthAgoData.find({PurchaseDate:{$gte:monthData}});

This will produce the following output −

{ "_id" : ObjectId("5e04e16c150ee0e76c06a04f"), "CustomerName" : "Chris", "PurchaseDate" : ISODate("2019-12-26T00:00:00Z") }
{ "_id" : ObjectId("5e04e186150ee0e76c06a051"), "CustomerName" : "Bob", "PurchaseDate" : ISODate("2020-11-26T00:00:00Z") }
raja
Published on 27-Mar-2020 12:22:26
Advertisements