MongoDB ไม่มี Auto Increment ตัวเลขในตัว ต้องสร้างคอลเลกชันเก็บค่าลำดับ (sequence) และฟังก์ชันเพื่อเพิ่มค่าและคืนค่าลำดับถัดไป
ขั้นตอนการทำงาน
- สร้างคอลเลกชันเก็บค่าลำดับ (เช่น
createSequenceDemo) พร้อมฟิลด์_idและS_Value - สร้างฟังก์ชัน
nextSequence()ใช้findAndModify()เพื่อเพิ่มค่าและคืนค่าล่าสุด - ใช้ฟังก์ชันนี้เวลา insert เอกสารใหม่
ตัวอย่างโค้ด
> db.createSequenceDemo.insertOne({_id:"SID",S_Value:0});
{ "acknowledged" : true, "insertedId" : "SID" }
> function nextSequence(s) {
... var sd = db.createSequenceDemo.findAndModify({
... query:{_id: s },
... update: {$inc:{S_Value:1}},
... new:true
... });
... return sd.S_Value;
... }
ใช้งานเมื่อ insert ข้อมูลนักศึกษา:
> 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") }
แสดงผลลัพธ์ (StudentId เพิ่มขึ้นทีละ 1):
> 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 }