5

how can I write filter which results docs created today.I know ObjectId has timestamp. I tried this :

db.doc.find({_id : { $gte : ObjectId().getTimestamp().getTime() }}

Can I write

db.doc.find({'_id.getTimestamp().getTime()' : { $gte : ObjectId().getTimestamp().getTime() }}
Community
  • 1
  • 1
Praveen Singh Yadav
  • 1,831
  • 4
  • 20
  • 31

2 Answers2

10

Try the following (based on this answer). This returns all documents created since the given date. So it covers todays entries as well.

db.doc.find({_id : { $gt : ObjectId(Math.floor(new Date('2014/01/30')/1000).toString(16)+"0000000000000000") }})

If you don't like to enter the date as string, you can create it via Objects, but it gets a little bit ugly:

db.doc.find({_id : { $gt : ObjectId(Math.floor(new Date(new Date().getFullYear()+'/'+(new Date().getMonth()+1)+'/'+new Date().getDate())/1000).toString(16)+"0000000000000000") }})
Community
  • 1
  • 1
dersvenhesse
  • 6,276
  • 2
  • 32
  • 53
  • Thanks I used this,It worked for me db.sale.aggregate({ $match :{ firm :ObjectId("52e56c009dbc794999ea5c3d") } }, {$project : {day : {$dayOfMonth : '$date'},items :1,patient :1}}, {$match : {day: {$gte : new Date().getDate()}}}, {$unwind : "$items"}, {$group :{_id:"$_id" ,count :{$sum:1},patient:"$patient"} }) – Praveen Singh Yadav Jan 30 '14 at 21:05
0

use this query, you can easily get the document created today but we have a problem, The day(24h) starts now and ends at tomorrow this time

    let dateStart = new Date()
    let dateEnd = new Date()
    dateStart.setUTCHours(0,0,0,0)
    dateEnd.setUTCDate(23,59,59,999)
    db.doc.find({$and:[{appointmentDate:{$gt: dateStart}},{appointmentDate:{$lt: dateEnd}}]})
Rahul
  • 31
  • 7