Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

อัปเดต Single Field ใน Capped Collection MongoDB

Capped Collection คือ collection ขนาดคงที่ (fixed-size) ที่เก็บข้อมูลแบบ circular buffer (เก่าทิ้งเมื่อเต็ม) สามารถอัปเดต field ได้ปกติ แต่ ห้ามเพิ่มขนาด document (เช่นเพิ่ม field ใหม่, ขยาย array)

สร้าง Capped Collection และข้อมูลตัวอย่าง

> db.createCollection("Demo112", { capped: true, size: 14, max: 3 });
{ "ok" : 1 }
> db.demo112.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2ef47a9fd5fd66da21447e") }
> db.demo112.insertOne({"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2ef47e9fd5fd66da21447f") }
> db.demo112.insertOne({"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2ef4919fd5fd66da214480") }

คำอธิบาย Options:

  • capped: true: เปิดโหมด capped collection
  • size: 14: ขนาดสูงสุดใน bytes (รวม overhead ~14 bytes ต่อ doc)
  • max: 3: จำนวนเอกสารสูงสุด (ถึง size หรือ max ก่อน จะทิ้งเก่าสุด)

แสดงข้อมูลก่อนอัปเดต

> db.demo112.find();

ผลลัพธ์: Chris, David, David (3 docs)

Query อัปเดต Field ใน Capped Collection

> db.demo112.update(
  {Name: "David"},
  {$set: {Name: "Robert"}},
  {multi: true}
);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

คำอธิบาย:

  • Filter: {Name: "David"} - หาทุกคนชื่อ David
  • $set: {Name: "Robert"} - เปลี่ยนชื่อเป็น Robert (ขนาด string เปลี่ยนเล็กน้อย แต่ยังพอดี)
  • {multi: true} - อัปเดตทุกเอกสารที่ match (default false)

ผลลัพธ์หลังอัปเดต

> db.demo112.find();

ผลลัพธ์: Chris, Robert, Robert

ข้อจำกัดสำคัญของ Capped Collection

ใช้งานจริง: Logging, Metrics, Cache

// Log collection - เก็บ 100MB ล่าสุด
db.createCollection("logs", {capped: true, size: 100*1024*1024})

// TTL alternative (ปกติ collection + auto expire)
db.createCollection("sessions")
db.sessions.createIndex({createdAt: 1}, {expireAfterSeconds: 3600})

ตรวจสอบว่าเป็น Capped Collection

db.demo112.stats().capped  // true
db.demo112.isCapped()       // true

สรุป: Capped collection อัปเดต field ได้ถ้าขนาดไม่เพิ่ม เหมาะสำหรับ log, cache, time-series data ขนาดคงที่

การกระทำรองรับหมายเหตุ
Update field (ขนาดเท่าเดิม/เล็กลง)✓ ได้เช่น string → string สั้นกว่า, number → number
Update field (ขนาดใหญ่ขึ้น)✗ ErrorDocument growth not allowed
Insert ใหม่✓ ได้ทิ้งเก่าสุดเมื่อเต็ม
Delete✗ ไม่ได้ใช้ TTL index แทน
Sharding✗ ไม่ได้