mongodb second id field with auto increment

南楼画角 提交于 2021-01-27 17:37:25

问题


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


回答1:


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/



来源:https://stackoverflow.com/questions/38084238/mongodb-second-id-field-with-auto-increment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!