Eoin Murray
Eoin Murray

Reputation: 1955

node.js, mongo quick way to hold unique number

I want to let mongo hold an incrementing number for me such that I can call that number and then generate a string from it.

x = 1e10
x.toString(36).substring(2,7)

>>'dqpds'

I have a way to increment the number every time I call it from mongo

db.counter.update({ _id: 1 }, { $inc: { seq: 1 } }, {upsert: true}, 
    function(err, val){
    //...
})

But I want to set the number to something like 1e10 at the beginning such that I get a 5 character long string, But I would rather not have something more than one call to the database.

How to I set a default value for the upsert in mongo. Or do you have a more efficient way of generating a unique 5 - 6 character string?

Upvotes: 0

Views: 173

Answers (2)

coderLMN
coderLMN

Reputation: 3076

If you only need a unique id which is not necessarily sequential, you can use the first part of ObjectId.

From the above document there is a description:

ObjectId is a 12-byte BSON type, constructed using:

a 4-byte timestamp,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.

So you can do like this:

x = ObjectId().toString().subString(0,4)

This approach doesn't involve database IO, so the performance would be better. If you want to be more sure about its uniqueness, add the last 2 bytes of the counter to make a 6 character one.

Upvotes: 1

Asya Kamsky
Asya Kamsky

Reputation: 42352

There is a way to do this in MongoDB.

You use the findAndModify command and it's described in detail in exactly the context you are looking for here:

http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

Upvotes: 0

Related Questions