在 MongoDB 中自動增加儲存唯一使用者 ID 序列?


若要透過自動增加的方式在 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() 方法顯示集合中的所有文件。查詢如下 −

> 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”

更新日期: 30-Jul-2019

610 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.