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

前端 未结 4 545
心在旅途
心在旅途 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

    getTimestamp()

    The function you need is this one, it's included for you already in the shell:

    ObjectId.prototype.getTimestamp = function() {
        return new Date(parseInt(this.toString().slice(0,8), 16)*1000);
    }
    

    References

    Check out this section from the docs:

    • Extract insertion times from _id rather than having a separate timestamp field

    This unit test also demostrates the same:

    • mongo / jstests / objid6.js

    Example using the Mongo shell:

    > db.col.insert( { name: "Foo" } );
    > var doc = db.col.findOne( { name: "Foo" } );
    > var timestamp = doc._id.getTimestamp();
    
    > print(timestamp);
    Wed Sep 07 2011 18:37:37 GMT+1000 (AUS Eastern Standard Time)
    
    > printjson(timestamp);
    ISODate("2011-09-07T08:37:37Z")
    

提交回复
热议问题