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

MongoDB: จำกัดจำนวนสมาชิกในอาร์เรย์ (Capped Sub-collection) ด้วย $slice

MongoDB ไม่รองรับ capped collection สำหรับ sub-collection (อาร์เรย์ภายในเอกสาร) โดยตรง แต่สามารถใช้ $slice ใน aggregation เพื่อจำกัดจำนวนสมาชิกที่ต้องการดึงมาแสดง สร้างคอลเลกชันตัวอย่าง:

> db.demo319.insertOne({"Scores":[100,345,980,890]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50ecf6f8647eb59e562064") }
> db.demo319.insertOne({"Scores":[903,10004,84575,844]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50ed01f8647eb59e562065") }

แสดงข้อมูล:

> db.demo319.find().pretty();

คิวรีใช้ $slice ดึงแค่ 2 ค่าแรกของอาร์เรย์ Scores:

> db.demo319.aggregate([
  { $project: { TwoScores: { $slice: [ "$Scores", 2 ] } } }
])

ผลลัพธ์:

{ "_id" : ObjectId("5e50ecf6f8647eb59e562064"), "TwoScores" : [ 100, 345 ] }
{ "_id" : ObjectId("5e50ed01f8647eb59e562065"), "TwoScores" : [ 903, 10004 ] }

รูปแบบ $slice

  • { $slice: [ <array>, <n> ] }: ดึง n ตัวแรก (n > 0) หรือ n ตัวสุดท้าย (n < 0)
  • { $slice: [ <array>, <skip>, <limit> ] }: ข้าม skip ตัว แล้วดึง limit ตัว
  • ใช้ได้ใน $project, $addFields, $set

หมายเหตุ

หากต้องการจำกัดขนาดอาร์เรย์ตอน insert/update ให้ใช้ $push ร่วม $slice ใน update operation เช่น { $push: { scores: { $each: [...], $slice: -10 } } } จะเก็บแค่ 10 ค่าล่าสุด