MongoDB实现ID自增长
2017-04-06 00:00
344 查看
参考1
参考2
实现方式主要是利用MongoDB中findAndModify命令,只要每次往MongoDB里insert对象前生成ID赋值给_id就OK了,因为它的实现满足原子性,所以不存在并发问题。findAndModify本身提供了一个upsert参数,为true的话可以自动insert,但那样就不能自定义初始值了,所以不使用upsert。
另,数据库“_seq”的名字以下划线开头,这样列表的时候会排在前面,容易分辨。
实现步骤如下:
参考2
实现
假设要为CollectionB实现自增长ID, 需要引入另外一个专门计算ID的CollectionA. A中存放一条记录:{'_id':'CollectionB', 'currentIdValue':1}, 其中currentIdValue表示CollectionB的当前最大id值+1,每次往CollectionB里插入数据前,先到CollectionA查询currentIdValue 值并把这个值+1。实现方式主要是利用MongoDB中findAndModify命令,只要每次往MongoDB里insert对象前生成ID赋值给_id就OK了,因为它的实现满足原子性,所以不存在并发问题。findAndModify本身提供了一个upsert参数,为true的话可以自动insert,但那样就不能自定义初始值了,所以不使用upsert。
另,数据库“_seq”的名字以下划线开头,这样列表的时候会排在前面,容易分辨。
实现步骤如下:
> db.CollectionA.insert({'_id':'CollectionB', 'currentIdValue':0}) WriteResult({ "nInserted" : 1 }) > > ID=db.CollectionA.findAndModify( {update:{$inc:{"currentIdValue":1}}, query:{"_id":"CollectionB"}, new:true} ) { "_id" : "CollectionB", "currentIdValue" : 1 } > > db.user.save( {_id:ID.currentIdValue, uid:ID.currentIdValue, username:"zhangsan", password:"password123", info:"Test User1"} ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > > ID=db.CollectionA.findAndModify( {update:{$inc:{"currentIdValue":1}}, query:{"_id":"CollectionB"}, new:true} ) { "_id" : "CollectionB", "currentIdValue" : 2 } > > db.user.save( {_id:ID.currentIdValue, uid:ID.currentIdValue, username:"lisi", password:"test1234567", info:"Test User2"} ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > > db.user.find() { "_id" : 1, "uid" : 1, "username" : "zhangsan", "password" : "password123", "info" : "Test User1" } { "_id" : 2, "uid" : 2, "username" : "lisi", "password" : "test1234567", "info" : "Test User2" } > > db.CollectionA.find() { "_id" : "CollectionB", "currentIdValue" : 2 } > > # 执行命令增加值 > db.runCommand({findAndModify:'CollectionA',query:{_id:'CollectionB'}, update:{$inc:{'currentIdValue':1}}, new:true}); { "lastErrorObject" : { "updatedExisting" : true, "n" : 1 }, "value" : { "_id" : "CollectionB", "currentIdValue" : 3 }, "ok" : 1 } > > db.CollectionA.find() { "_id" : "CollectionB", "currentIdValue" : 3 }
相关文章推荐
- Mongodb 自动增长 自增id 实现
- MongoDB自动增长id实现、自定义函数调用、与Spring集成
- Mongodb 自动增长 自增id 实现
- Mongodb 自动增长 自增id 实现 -1
- MongoDB自动增长id实现、自定义函数调用、与Spring集成
- Mongodb 自动增长 自增id 实现 -2
- MongoDB 实现字段自动增长id Mongodb auto increment ID
- Mongodb 自动增长 自增id 实现
- Mongodb 自动增长 自增id 实现 -3 PHP
- MongoDB自增长ID的实现
- Spring-boot mongodb ID自增长注解实现 适用于JDK 1.7和JDK 1.8
- MySQL中自定义函数实现id自增长
- mongoDB 自增ID C++实现方法
- 一个通用的单元测试框架的思考和设计07-实现篇-自动管理测试数据-如何为自增长主键id赋值
- ASP.NET MVC4下使用MongoDB实现时间戳和ObjectId相互转换
- mongodb使用-增删改查、colleciton关联、_id作为主键实现update
- oracle 序列 + 触发器 实现 ID自动增长
- 分布式自增长ID(Twitter的 Snowflake JAVA实现方案 )
- oracle实现id自增长
- 如何使用MongoDB+Springboot实现分布式ID?