Can I query MongoDB ObjectId by date ?



  • 3 Answer(s)

    Short code for JavaScript:

    // This function returns an ObjectId embedded with a given datetime
    // Accepts both Date object and string input
    function objectIdWithTimestamp(timestamp) {
        // Convert string date to Date object (otherwise assume timestamp is a date)
        if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
        }
        // Convert date object to hex seconds since Unix epoch
        var hexSeconds = Math.floor(timestamp/1000).toString(16);
        // Create an ObjectId with that hex timestamp
        var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
        return constructedObjectId
    }
    // Find all documents created after midnight on May 25th, 1980
    db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });
    

     

    Answered on January 4, 2019.
    Add Comment

    In pymongo, it can be done this way:

    import datetime
    from bson.objectid import ObjectId
    mins = 15
    gen_time = datetime.datetime.today() - datetime.timedelta(mins=mins)
    dummy_id = ObjectId.from_datetime(gen_time)
    result = list(db.coll.find({"_id": {"$gte": dummy_id}}))
    
    Answered on January 4, 2019.
    Add Comment

    For that to using a inbuilt function provided by mongodb drivers in in Node.js lets you query by any timestamp:

    var timestamp = Date.now();
    var objectId = ObjectID.createFromTime(timestamp / 1000);
    

    As another option, to search for records before the current time, you can simply do:

    var objectId = new ObjectID(); // or ObjectId in the mongo shell
    

    To Reference: http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html

     

    Answered on January 4, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.