Skip to content

Instantly share code, notes, and snippets.

@solenoid
Created November 17, 2011 04:49
Show Gist options
  • Save solenoid/1372386 to your computer and use it in GitHub Desktop.
Save solenoid/1372386 to your computer and use it in GitHub Desktop.
javascript ObjectId generator
var mongoObjectId = function () {
var timestamp = (new Date().getTime() / 1000 | 0).toString(16);
return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function() {
return (Math.random() * 16 | 0).toString(16);
}).toLowerCase();
};
@berdfandrade
Copy link

A simple python implementation

import time
import random

def mongo_object_id():
    timestamp = hex(int(time.time()))[2:]
    rest = ''.join([random.choice('0123456789abcdef') for _ in range(16)])
    
    return (timestamp + rest).lower()

@Myllaume
Copy link

I use console.log(new (require('bson').ObjectId)().toString()).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment