为了在MongoDB中自动递增以存储唯一的用户ID序列,让我们创建一个集合,其中包含有关所有文档的最后序列值的信息。
让我们首先创建一个集合。创建一个集合的查询如下-
> db.createSequenceDemo.insertOne({_id:"SID",S_Value:0}); { "acknowledged" : true, "insertedId" : "SID" }
现在,我们将创建一个函数,该函数将在MongoDB中生成一个自动增量来存储序列。查询如下-
> function nextSequence(s) { ... var sd = db.createSequenceDemo.findAndModify({ ... query:{_id: s }, ... update: {$inc:{S_Value:1}}, ... new:true ... }); ... return sd.S_Value; ... }
让我们创建一个包含一些文档的集合,并调用上面的函数以生成一系列唯一的用户ID。
使用文档创建集合的查询如下-
> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Larry","StudentMathMarks":78}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f61008d10a061296a3c40") } > db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Mike","StudentMathMarks":89}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f61118d10a061296a3c41") } > db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Sam","StudentMathMarks":67}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f611d8d10a061296a3c42") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.checkSequenceDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c7f61008d10a061296a3c40"), "StudentId" : 1, "StudentName" : "Larry", "StudentMathMarks" : 78 } { "_id" : ObjectId("5c7f61118d10a061296a3c41"), "StudentId" : 2, "StudentName" : "Mike", "StudentMathMarks" : 89 } { "_id" : ObjectId("5c7f611d8d10a061296a3c42"), "StudentId" : 3, "StudentName" : "Sam", "StudentMathMarks" : 67 }
查看自动增加1的字段“ StudentId”