DEV Community

Cover image for How to query date range in Mongo
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

7 1

How to query date range in Mongo

Use only the date1 part

In the following example only the date part is set. Time is set to by default to 00:00:00. So the following query compares all entries archived within a day (2021-06-14):

var start = new Date("2021-06-14");
var end = new Date("2021-06-15");

db.call_archive.find({
  archivedAt: {$gte: start, $lt: end}
}).pretty();

Enter fullscreen mode Exit fullscreen mode

Use both date and time

You can also specify the Time in ISO format

  • new Date("<YYYY-mm-ddTHH:MM:ss>") - specifies the datetime in the client's local timezone and returns the ISODate with the specified datetime in UTC
  • new Date("<YYYY-mm-ddTHH:MM:ssZ>") - specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC
var start = new Date("2021-06-14");
var end = new Date("2021-06-15");

db.call_archive.find({
  archivedAt: {$gte: start, $lt: end}
}).sort({archivedAt: -1}).pretty(); //sort descending

Enter fullscreen mode Exit fullscreen mode

Shared with ❤️ from Codever. 👉 Use the Copy to mine functionality to copy the snippet to your own personal collection and easy manage your code snippets.


  1. https://docs.mongodb.com/manual/reference/method/Date/ 

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay