How do I extract the created date out of a Mongo ObjectID

前端 未结 4 548
心在旅途
心在旅途 2020-12-04 08:23

I\'m using the Mongo shell to query my Mongo db. I want to use the timestamp contained in the ObjectID as part of my query and also as a column to extract into output. I h

4条回答
  •  情歌与酒
    2020-12-04 08:48

    To use the timestamp contained in the ObjectId and return documents created after a certain date, you can use $where with a function.

    e.g.

    db.yourcollection.find( { 
      $where: function() { 
        return this._id.getTimestamp() > new Date("2020-10-01")
      } 
    });
    

    The function needs to return a truthy value for that document to be included in the results. Reference: $where

    Mongo date objects can seem a bit peculiar though. See the mongo Date() documentation for constructor details.

    excerpt:

    You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
    
        new Date("") returns the ISODate with the specified date.
        new Date("") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
        new Date("") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
        new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.
    
    

提交回复
热议问题