Blog

Auto-Increment Sequence trong MongoDB

MongoDB không có tính năng out-of-the-box auto-increment giống SQL Database. Theo mặc định, nó sử dụng ObjectId có độ dài 12 byte cho trường _id như Primary key để nhận diện một cách duy nhất các Document. Tuy nhiên, có các tình huống khi chúng ta muốn trường _id có một số giá trị có thể tự động tăng ngoài ObjectId.

Vì điều này không là tính năng mặc định trong MongoDB, chúng ta sẽ chương trình hóa tính năng này bởi sử dụng một counters collection như đã đề nghị bởi MongoDB Documentation.

Sử dụng counter Collection

Bạn theo dõi products document sau. Chúng ta muốn trường _id là một dãy số nguyên tự động tăng dần bắt đầu từ 1, 2, 3, 4 đến n.

{
  "_id":1,
  "product_name": "Apple iPhone",
  "category": "mobiles"
}

Để làm điều này, tạo một counters collection để theo dõi giá trị dãy cuối cùng cho tất cả các trường sequence.

>db.createCollection("counters")

Bây giờ, chúng ta sẽ chèn Document sau trong counters Collection với productid là key của nó.

{
  "_id":"productid",
  "sequence_value": 0
}

Trường sequence_value theo dõi giá trị cuối cùng của dãy đó.

Sử dụng code sau để chèn sequence document này vào trong counters collection:

>db.counters.insert({_id:"productid",sequence_value:0})

Tạo hàm JavaScript

Bây giờ, chúng ta sẽ tạo một hàm getNextSequenceValue, mà nhận tên dãy như là đầu vào của nó, tăng giá trị dãy thêm 1 và trả về số đã được cập nhật. Trong ví dụ này, tên dãy là productid.

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

Sử dụng hàm JavaScript

Giờ chúng ta sử dụng hàm getNextSequenceValue trong khi tạo một Document mới và gán giá trị dãy đã trả về như là trường _id của Document đó.

Chèn hai Document mẫu bởi sử dụng code sau:

>db.products.insert({
   "_id":getNextSequenceValue("productid"),
   "product_name":"Apple iPhone",
   "category":"mobiles"})

>db.products.insert({
   "_id":getNextSequenceValue("productid"),
   "product_name":"Samsung S3",
   "category":"mobiles"})

Như bạn thấy, chúng ta đã sử dụng hàm getNextSequenceValue để thiết lập giá trị cho trường _id.

Để kiểm tra tính năng này, chúng ta lấy các Document bởi sử dụng lệnh find:

>db.prodcuts.find()

Truy vấn trên trả về các Document có trường _id là tự động tăng.

{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}

{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }

Leave a Reply

Your email address will not be published. Required fields are marked *

slot88 slot4d slot4d slot4d sv388 slot88 suhubet demo slot slot4d demo slot https://fabritec.pe/asesor.php suhubet bujangjp https://kibf.pk/ slotsensa buku303 totogacor slot4d sbobet sv388 sv388 slot gacor Slot Gacor toto gacor slot gacor slot thailand slot jepang totogacor slot thailand slot thailand situs gacor malam ini slot luar negeri slot gacor 4d totogacor slot gacor wd jutaan slotsensa totogacor totogacor demo slot slot 4d totogacor totogacor demo slot totogacor slot thailand totogacor bujangjp situs gacor situs gacor Situs Gacor 4D Thailand Situs Gacor 4D