MongoDB 按“数字”排序上升
我正在尝试使用 mongoose 和 MongoDB 创建一个注册表单。我有一个唯一的键 UserId,每次创建新条目时,我都想获取数据库中最大的 UserId 并将其加一。 我尝试使用 db.user.find({}).sort({userId: 1});
但似乎不起作用。 谢谢马西亚尔
I'm trying to create a registration form with mongoose and MongoDB. I have a unique key, UserId, and every time I create a new entry I would like to take the greatest UserId in the database and increase it by one.
I tried with db.user.find({}).sort({userId: 1});
but it seems not to work.
Thanks
Masiar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要做的听起来更像是具有自动增量的关系数据库架构。我会推荐另一种解决方案。
一开始你已经有一个唯一的ID。它会自动创建并位于“_id”字段中。对我来说,您似乎想要一个 UserID 来建立关系,但您已经可以使用 _id 中的值。
您想要增加 id 的另一件事可能是您创建了一个 Web 应用程序并且可能想要“更好”的 url?例如。 /user/1 而不是 /user/abc48df...?
如果是这种情况,我宁愿对用户名创建唯一约束。您可以在 url“/user/john”中使用您的用户名,而不是 ID。
这样你的网址就好多了。为了建立关系,您可以使用 _id。而且你不会遇到首先计算出最高数字的问题。
创建唯一索引:
What you want to do sounds more like a Schema for Relational Databases with an Auto Increment. I would recommend another solution.
At first you already have a unique id. It get automatically created and are in "_id" field. For me it seems you want to have a UserID for building relation, but you already ca use the value in _id.
The other thing why you want incremented ids could be that you create a webapplication and propably want "nicer" urls? For example. /user/1 instead of /user/abc48df...?
If that is the case i would prefer to create a unique constraint on a username. And instead of an id you use you username in the url "/user/john".
With this your urls are much nicer. And for building relation you can use _id. And you don't run into problems with fethcing the highest number first.
To create a unique index:
您可以这样做来获取当前具有最高
UserId
的用户:值得注意的是,MongoDB 中没有办法获取该值并在单个原子事务中插入新用户,它只能支持对单个文档的原子操作。您需要注意另一个操作不会同时插入另一个用户,否则最终可能会出现两个具有相同 UserId 的用户。
要迭代光标并将返回的文档放入数组中:
You can do this to get the user with the current highest
UserId
:It's worth noting that there isn't a way in MongoDB to fetch this value and insert a new user in a single atomic transaction, it only supports atomic operations on single documents. You'd need to take care that another operation didn't insert another user at the same time, you could end up with two users with the same UserId.
To iterate over the cursor and get put the returned doc in an array: