ortusolis
ortusolis

Reputation: 85

How to Create a custom objectID in mongodb

As far as i know, you can call ObjectId("something"); to generate a new id.

Is it possible to generate a random id, which does not already exist in the database/collection and has a specific format?

In my case, i want object id to generate a unique random 10digit number.

So the result should be:

var ObjectId = require('mongodb').ObjectID
var id = new ObjectId("something");
console.log(id) ==> 0123456789   

Upvotes: 1

Views: 2945

Answers (1)

Adrian
Adrian

Reputation: 8597

As in the comments, your best bet would be to get seconds into the current year when inserting the document. But the real question would be how intensive would insertion of new documents be. You need to account for multiple factors, first being the more documents you insert, the higher the chance your ids will collide at one point.

I would recommend just leaving the standard GUID mongo generates for you, however a solution that I can think of from top of my head would be getting the seconds into the current year, substring that to get the last 5 digits, and then generate 5 random digits and merge them together.

new Date().getTime().toString().substring(8) + Math.floor(Math.random() * (99999 - 10000)) + 100000;

With the above (80 bits) you would get 4.135898×10-13 collision probability on 1000000 documents.

Upvotes: 2

Related Questions