如何在MongoDB中使用自动增量设置主键?

Ven*_*nks 19 primary-key mongodb

如何在MongoDB中使用自动增量设置主键?

通常MongoDB生成ObjectID.我想使用我自己的自动增量主键,如MySQL.

例子将不胜感激:)

Ale*_*lex 9

我在这里写了博客:http:
//www.alexjamesbrown.com/blog/development/mongodb-incremental-ids/

我还为C#驱动程序启动了一个int id生成器:https:
//github.com/alexjamesbrown/MongDBIntIdGenerator

但是,递增ID不会有效扩展.

  • 因为每个节点都必须经常知道"最新"的ID ...然而,Twitter'雪花'为此提供了解决方案.另外,请阅读 - https://blog.serverdensity.com/switching-to-mongodb-and-auto-increment/ (2认同)

小智 6

$db->execute("return db.getCollection('autoInccollection').findAndModify({
                        query: { collection: '$colle' },
                        update: { '$inc': { primaryKey: 1 } },new: true
                            })");
Run Code Online (Sandbox Code Playgroud)

$ colle表示创建自动增量键所需的集合.