mongo-16.自定义自增id

文章目录

创建函数

rsb:PRIMARY> function getNextSequence(sequenceName){
...  var sequenceDocument = db.counters.findAndModify(
... {
...  query:{_id: sequenceName },
... update: {$inc:{sequence_value:1}},
...  "new":true
... });
... return sequenceDocument.sequence_value;
... }
rsb:PRIMARY> 

rsb:PRIMARY> db.createCollection("counters")
{
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1672223043, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1672223043, 1)
}
rsb:PRIMARY> db.counters.insert({_id:'hello',sequence_value:0})
WriteResult({ "nInserted" : 1 })
rsb:PRIMARY> var id=getNextSequence('hello')
rsb:PRIMARY> id
1
rsb:PRIMARY> id=getNextSequence('hello')
2
rsb:PRIMARY> id=getNextSequence('hello2')
uncaught exception: TypeError: sequenceDocument is null :
getNextSequence@(shell):8:1
@(shell):1:4

插入初始值

rsb:PRIMARY> db.counters.insert({_id:"productid",sequence_value:0})
WriteResult({ "nInserted" : 1 })

db.tutorials.insert({
 "_id":getNextSequence("productid"),
 "tutorials_name": "MongoDB 教程",
 "url": "http://www.biancheng.net/mongodb/index.html",
 "author": "编程帮"
 })
db.tutorials.insert({
 "_id":getNextSequence("productid"),               
 "tutorials_name": "HTML 教程",
 "url": "http://www.biancheng.net/html/index.html",
 "author": "编程帮"
 })

查询

rsb:PRIMARY> db.tutorials.find().pretty()
{
        "_id" : 1,
        "tutorials_name" : "MongoDB ",
        "url" : "http://www.biancheng.net/mongodb/index.html",
        "author" : ""
}
{
        "_id" : 2,
        "tutorials_name" : "HTML ",
        "url" : "http://www.biancheng.net/html/index.html",
        "author" : ""
}
rsb:PRIMARY> 


版权声明:本文为qq_24223159原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>