Is there any way to create mongodb like _id strings without mongodb?


Question

I really like the format of the _ids generated by mongodb. Mostly because I can pull data like the date out of them client side. I'm planning to use another database but still want that type of _id for my document. How can I create these ids without using mongodb?

Thanks!

1
18
9/22/2017 5:57:57 PM

Accepted Answer

Object IDs are usually generated by the client, so any MongoDB driver would have code to generate them.

If you're looking for JavaScript, here's some code from the MongoDB Node.js driver:

https://github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js

And another, simpler solution:

https://github.com/justaprogrammer/ObjectId.js

19
5/26/2018 8:40:23 PM

A very easy pseudo ObjectId generator in javascript:

const ObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) =>
    s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon