Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb second id field with auto increment

I want to have an additional ID field in my mongodb collection. The objectId is perfect for get unique IDs, but I need shorter IDs for my user management. These IDs should look like 100001, 100002 and so on. Is it possible to get these by auto increment?

Thx

like image 472
ym-b Avatar asked Sep 10 '25 07:09

ym-b


1 Answers

MongoDB does not have an auto increment functionality.

You could solve this by keeping track the 'id' in a separate collection called 'user_sequence' and store a custom function in MongoDB to get the next value.

Take a look at: https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/

Create a query like:

db.users.insert({
    userid: sequenceNextValue("userid")
})

Step by step tutorial by MongoDB: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/

like image 190
Kevin Avatar answered Sep 13 '25 04:09

Kevin