MongoDB find Query comparision with CurrentDate

As per your question you want to fetch current day documents from a mongodb collection. In mongoDB shell when you type new Date() it gives you current date with time and this value always vary when you run same new Date() so probably your query like this :

db.collectionName.find({"start_date":new Date()}).pretty()

But, I think this query return the those documents which will presents in your collection but same current Date value may be not presents in your documents SO this case you should use following

db.collectionName.find({"start_date":{"$lte":new Date()}}).pretty()

Or

db.collectionName.find({"start_date":{"$gte":new Date()}}).pretty()

In some case If you want to find exact match with year,month,day then you should use aggregation with $year,$month,$dayOfMonth in $project like this :

db.collectionName.aggregate({
  "$project": {
    "year": {
      "$year": "$date"
    },
    "month": {
      "$month": "$date"
    },
    "day": {
      "$dayOfMonth": "$date"
    }
  }
}, {
  "$match": {
    "year": new Date().getFullYear(),
    "month": new Date().getMonth() + 1, //because January starts with 0
    "day": new Date().getDate()
  }
})

In above aggregation query will return those documents which match current date like year,month,day of current date. Also you replace $match as

var currentDate = new Date()

 {
  "$match": {
    "year": currentDate.getFullYear(),
    "month": currentDate.getMonth() + 1, //because January starts with 0
    "day": currentDate.getDate()
  }
}

If you are using Mongoose you can include timeStamp: true after your schema definition to get autogenerated createdAt and updatedAt fields, Mongoose will take care of it.

const itemSchema = mongoose.Schema({
    // Your Schema definition here
}, {
  timestamps: true
})

In your case, you need to compare your TimeStamp key with the start of today which is 12 AM with ISO string as 2019-11-08T00:00:00.000Z and end of the day which is 11:59 PM with ISO string as 2019-11-08T23:59:59.999Z.
The below code will do it for you.

let queryObj = {}
const startOfDay = new Date(new Date().setUTCHours(0, 0, 0, 0)).toISOString()
const endOfDay = new Date(new Date().setUTCHours(23, 59, 59, 999)).toISOString()
    
queryObj.createdAt = {
  $gte: startOfDay, // 2019-11-08T00:00:00.000Z
  $lt: endOfDay // 2019-11-08T23:59:59.999Z
}

let items = item.find(obj)
// new Date().setUTCHours(0, 0, 0, 0) Generates this weird string '1573171200000' which is not a human readable format of TimeStamp
// To convert it into ISO String we have .toISOString() method 

Tags:

Mongodb