MongoDB实现ID自增长

参考1 参考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 }


转载于:https://my.oschina.net/u/588736/blog/873877

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值