CURDATE() function like in mysql for mongoDB

624 views Asked by At

Have seen that new Date() will display the current date with time. But I need only date part.

 new Date()
ISODate("2015-06-11T06:49:17.684Z")

I need only date part--> ISODate("2015-06-11T00:00:00.000Z")

Below is the sample data:

{
  "_id": ObjectId("55743942789a9abe7f4af40e"),
  "msisdn": "9xxxxxxxxx",
  "act_date": ISODate("2014-09-16T00:00:00Z"),
  "date": ISODate("2015-06-07T00:00:00Z"),
  "recharge": {
    "recharge_amt": 100,
    "rechargetype": "WEB"
  },
  "voice": {
    "local_og_mou": 4,
    "local_other_mobile_og_mou": 18,
    "nld_og_mou": 10,
    "nld_other_mobile_og_mou": 3
  },
  "gprs_usage": {
    "total_access_count": 1,
    "total_datavolume_mb": 63
  },
  "sms": {
    "freesms": 0,
    "local_sms_count": 0,
    "nat_sms_count": 2,
    "inter_sms_count": 0
  }
}

Need to Fetch current day data based on date field. Is there any CURDATE() function like in mysql for mongoDB?

3

There are 3 answers

1
AudioBubble On BEST ANSWER

Well you can "round" the date object to the current day:

new Date( new Date().valueOf() - new Date().valueOf() % ( 1000 * 60 * 60 * 24 ) )

Of course, there are varying language dependant ways to "round" your date, but this is a JavaScript way.

0
chridam On

One approach you could take is using the momentjs library, in particular the .startOf('day') method:

var currentDate = moment().startOf('day').toDate();

db.colection.find({"date": currentDate}) 
0
Sylvain Leroux On

Just in order to be a little bit more robust, I would use range query instead of an exact match to query dates (imagine some client having updated the data using $currentDate for example):

// @user3561036 code:
var theDate = new Date( new Date().valueOf() - new Date().valueOf() % ( 1000 * 60 * 60 * 24 )

// One day later:
var theDayAfter = new Date(theDate.valueOf() + 1000 * 60 * 60 * 24)


// Search for date in the range `[theDate, theDayAfter)`
db.colection.find({"date": { $gte: theDate, $lt: theDayAfter } })