Mongoose: Find documents since last day, last week, last month

Updated: December 30, 2023 By: Guest Contributor Post a comment

Learn how to query documents using Mongoose by time frame – last day, last week, and last month – with Node.js and JavaScript.

Setting Up the Environment

Create a new Node.js project, install Mongoose, and connect to a MongoDB instance. Define a Mongoose schema to model your data with a date field.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourdb', { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;

const dataSchema = new Schema({
  // ... other fields ...
  createdAt: { type: Date, default: Date.now },
});

Finding Documents by Date

Last Day (24 Hours)

Use the find() function with a dynamic date object to retrieve documents from the last 24 hours.

const DataModel = mongoose.model('Data', dataSchema);

async function findLastDayDocuments() {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  
  return await DataModel.find({
    createdAt: { $gte: yesterday }
  }).exec();
}

You can also create custom query helpers to encapsulate the process of querying by time frames:

dataSchema.query.byLastDay = function() {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  return this.find({ createdAt: { $gte: yesterday } });
};

// Usage
DataModel.find().byLastDay().exec();

Last Week (7 Days)

Similar to the last day, adjust the date to target documents created within the last week.

async function findLastWeekDocuments() {
  const lastWeek = new Date();
  lastWeek.setDate(lastWeek.getDate() - 7);
  
  return await DataModel.find({
    createdAt: { $gte: lastWeek }
  }).exec();
}

Last Month

To fetch documents from the last month, calculate the date object accordingly.

async function findLastMonthDocuments() {
  const lastMonth = new Date();
  lastMonth.setMonth(lastMonth.getMonth() - 1);
  
  return await DataModel.find({
    createdAt: { $gte: lastMonth }
  }).exec();
}

Error Handling with Async/Await

When using Async/Await, make sure to handle errors with try/catch blocks to keep your application stable.

async function safeFindLastWeekDocuments() {
  try {
    return await findLastWeekDocuments();
  } catch (error) {
    // handle error
  }
}

Advanced Queries with Aggregation

Use Mongoose’s aggregation framework for more complex time-based queries, such as grouping documents by the week.

async function aggregateDocumentsByWeek() {
  return await DataModel.aggregate([
    {
      $match: {
        createdAt: { $gte: /* your start date */ }
      }
    },
    {
      $group: {
        _id: { week: { $week: '$createdAt' } },
        count: { $sum: 1 }
      }
    }
  ]);}

Conclusion

This tutorial introduced you to time-based document retrieval in Mongoose, iterating from basic to advanced queries. Apply these techniques to make your application’s data querying efficient and powerful.