Getting MongoDB results from the previous month

To get MongoDB results from the previous month, first get the current date and subtract one month from it. This creates a date boundary to filter records that fall within the previous month period.

Syntax

var previousMonth = new Date();
previousMonth.setMonth(previousMonth.getMonth() - 1);
db.collection.find({dateField: {$gte: previousMonth}});

Sample Data

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

Display All Documents

db.findOneMonthAgoData.find();
{ "_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") }

Example: Get Previous Month Results

Create a date variable and subtract one month to filter records from the previous month ?

monthData = new Date();
monthData.setMonth(monthData.getMonth() - 1);
db.findOneMonthAgoData.find({PurchaseDate: {$gte: monthData}});
{ "_id": ObjectId("5e04e16c150ee0e76c06a04f"), "CustomerName": "Chris", "PurchaseDate": ISODate("2019-12-26T00:00:00Z") }
{ "_id": ObjectId("5e04e186150ee0e76c06a051"), "CustomerName": "Bob", "PurchaseDate": ISODate("2020-11-26T00:00:00Z") }

Key Points

  • setMonth() method automatically handles year rollover when subtracting months
  • $gte operator finds documents with dates greater than or equal to the calculated previous month date
  • The query returns all records from the previous month onwards, not just the exact previous month

Conclusion

Use JavaScript's Date methods with MongoDB's date comparison operators to filter documents from the previous month. The setMonth() method provides a simple way to calculate the previous month boundary for date-based queries.

Updated on: 2026-03-15T01:48:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements