具有自动增量的mongodb第二个ID字段 [英] mongodb second id field with auto increment
问题描述
我想在mongodb集合中有一个附加的ID字段.objectId非常适合获得唯一的ID,但是我需要为用户管理使用较短的ID.这些ID应该类似于 100001
, 100002
等.是否可以通过自动递增获取这些信息?
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
推荐答案
MongoDB没有自动递增功能.
MongoDB does not have an auto increment functionality.
您可以通过在名为"user_sequence"的单独集合中跟踪"id"并在MongoDB中存储自定义函数以获得下一个值来解决此问题.
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.
看看: https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/
创建一个查询,例如:
db.users.insert({
userid: sequenceNextValue("userid")
})
MongoDB的分步教程: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/
Step by step tutorial by MongoDB: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/
这篇关于具有自动增量的mongodb第二个ID字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!