Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query mongodb to return documents created today

Tags:

mongodb

nosql

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() }}
like image 983
Praveen Singh Yadav Avatar asked Jan 30 '14 18:01

Praveen Singh Yadav


People also ask

How do I get today in MongoDB?

The current date in the MongoDB query The following two ways return date as a string or as a date object: The Date() will return the current date as a string. The new Date() will return the current date a date object and MongoDB cover the Date object with the ISODate.

How do I query a document in MongoDB?

The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.

How do I get all my documents from MongoDB?

Connect to a database using the getDatabase() method. Get the object of the collection from which you want to retrieve the documents, using the getCollection() method. Retrieve the iterable object containing all the documents of the current collection by invoking the find() method.

What does MongoDB query return?

find() in MongoDB? The statement db. collection. find() returns the cursor of Result Set of a query by which you can iterate over the result set or print all documents.


1 Answers

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") }})
like image 147
dersvenhesse Avatar answered Oct 06 '22 00:10

dersvenhesse