mongodb 如何在MongoDB中使用自动增量设置主键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18334279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set primary key with auto increment in MongoDB?
提问by Venks
How to set primary key with auto increment in MongoDB ?
如何在 MongoDB 中设置具有自动增量的主键?
Normally MongoDB generates ObjectID. I wanna use my own auto increment primary key like MySQL.
通常 MongoDB 生成 ObjectID。我想使用我自己的自动增量主键,比如 MySQL。
Examples would be appreciated :)
示例将不胜感激:)
回答by Alex
I blogged about this here:
http://www.alexjamesbrown.com/blog/development/mongodb-incremental-ids/
我在这里写了博客:http:
//www.alexjamesbrown.com/blog/development/mongodb-incremental-ids/
I also started a int id generator for the C# driver:
https://github.com/alexjamesbrown/MongDBIntIdGenerator
我还为 C# 驱动程序启动了一个 int id 生成器:https:
//github.com/alexjamesbrown/MongDBIntIdGenerator
However, incrementing ID's won't scale effectively.
但是,增加 ID 不会有效地扩展。
回答by Sanith
$db->execute("return db.getCollection('autoInccollection').findAndModify({
query: { collection: '$colle' },
update: { '$inc': { primaryKey: 1 } },new: true
})");
$colle means which collection you need to create the Auto increment key.
$colle 表示您需要创建自动增量键的集合。