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() }}

2 Answers 2

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") }})
1
  • 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"} }) Jan 30, 2014 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}}]})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.