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();
};
@vfa-tamhh
Copy link

Thanks! This code useful for me!

@cassiolacerda
Copy link

Thank you so much man!!!

@stubbyteam
Copy link

Thank you so much man!!!

@killshot13
Copy link

I appreciate that you shared this. It is a simple, logical function and integrates nicely with my Express backend.

@prakashsellathurai
Copy link

@solenoid what about the collision of this random id generation method?

@thauealfredo
Copy link

Perfect, thanks!!

@BathriNathan
Copy link

BathriNathan commented Oct 29, 2021

simple and quick solution. thanks

here is the function in coffee script:
mongoObjectId: () ->
timestamp = ((new Date).getTime() / 1000 | 0).toString(16)
timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, ->
(Math.random() * 16 | 0).toString 16
).toLowerCase()

@fabiofa87
Copy link

It saved my life. lol

Thanks dude!

@glafer
Copy link

glafer commented Feb 15, 2023

Thanks!

@m0k1
Copy link

m0k1 commented Jul 3, 2023

@pedrogardim
Copy link

Thanks a lot, it was very useful!

I made a Golang version for a project

func mongoObjectId() string {
	ts := time.Now().UnixMilli() / 1000
	id := strconv.FormatInt(ts, 16)
	for i := 0; i < 16; i++ {
		id += fmt.Sprintf("%x", rand.Intn(16))
	}
	return id
}

@pacifiquem
Copy link

Impl in rust:

use chrono::Utc;
use rand::Rng;
use std::fmt;

fn mongo_object_id() -> String {
    let ts = Utc::now().timestamp_millis() / 1000;
    let mut id = format!("{:x}", ts);
    
    for _ in 0..16 {
        let random_digit = rand::thread_rng().gen_range(0..16);
        id.push_str(&format!("{:x}", random_digit));
    }

    id
}

fn main() {
    let object_id = mongo_object_id();
    println!("{}", object_id);
}

// [dependencies]
// chrono = "0.4"
// rand = "0.8"

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