mongodb second id field with auto increment
10,421
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/
Author by
ym-b
Updated on June 04, 2022Comments
-
ym-b about 2 years
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