MongoDB/Mongoose querying at a specific date? MongoDB/Mongoose querying at a specific date? mongoose mongoose

MongoDB/Mongoose querying at a specific date?


That should work if the dates you saved in the DB are without time (just year, month, day).

Chances are that the dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day.

db.posts.find({ //query today up to tonight    created_on: {        $gte: new Date(2012, 7, 14),         $lt: new Date(2012, 7, 15)    }})


...5+ years later, I strongly suggest using date-fns instead

import endOfDayfrom 'date-fns/endOfDay'import startOfDay from 'date-fns/startOfDay'MyModel.find({  createdAt: {    $gte: startOfDay(new Date()),    $lte: endOfDay(new Date())  }})

For those of us using Moment.js

const moment = require('moment')const today = moment().startOf('day')MyModel.find({  createdAt: {    $gte: today.toDate(),    $lte: moment(today).endOf('day').toDate()  }})

Important: all moments are mutable!

tomorrow = today.add(1, 'days') does not work since it also mutates today. Calling moment(today) solves that problem by implicitly cloning today.


Yeah, Date object complects date and time, so comparing it with just date value does not work.

You can simply use the $where operator to express more complex condition with Javascript boolean expression :)

db.posts.find({ '$where': 'this.created_on.toJSON().slice(0, 10) == "2012-07-14"' })

created_on is the datetime field and 2012-07-14 is the specified date.

Date should be exactly in YYYY-MM-DD format.

Note: Use $where sparingly, it has performance implications.