Published on

How to filter documents by specific date range in MongoDB

Authors

Let's say you want to filter documents by a specific date range like the current month in MongoDB / Mongoose.

Here's how to do it:

Using Mongoose

// import MyExampleModel from './models/my-example-model.js';

const startOfMonth = new Date("2023-05-01");
const endOfMonth = new Date("2023-05-31");

const documents = await MyExampleModel.find({
  date: { $gte: startOfMonth, $lte: endOfMonth },
});

Using the MongoDB Client

// Assuming, the connection is handled and we've a "client" variable
// const client = new MongoClient(uri);

const collection = client.db("my-example-db").collection("example-collection");

const startOfMonth = new Date("2023-05-01");
const endOfMonth = new Date("2023-05-31");

const documents = await collection
  .find({
    date: { $gte: startOfMonth, $lte: endOfMonth },
  })
  .toArray();

Happy date-range Mongodb!