I want to retrieve values inserted on particular d

2019-02-20 04:30发布

问题:

I want to retrieve values inserted on particular date. Is this possible using mongodb "_id" field? as this contains embedded date time. I want to retieve values in mongodb shell not by using any application.

回答1:

While it is true that the ObjectId is based on a "timestamp" in part, generally this is a "client" library operation to "extract" this date from the ObjectId value.

You can do this with the JavaScript evaluation of $where, but it will need to "scan" the entire collection, so is not very efficient:

 db.collection.find(function() {
     return (
        ( this._id.getTimestamp().valueOf() - 
          this._id.getTimestamp().valueOf() % ( 1000 * 60 * 60 * 24 ) )
        == new Date("2014-07-14").valueOf() );
 })

That will basically compare to see if the ObjectId was created on the same day as the date provided. Other date math or methods apply to other intervals.