I want to retrieve values inserted on particular date using _id of mongodb

前端 未结 1 1427
逝去的感伤
逝去的感伤 2021-01-16 03:42

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

1条回答
  •  有刺的猬
    2021-01-16 04:22

    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.

    0 讨论(0)
提交回复
热议问题