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

MongoDB นับจำนวนค่าเฉพาะอย่างรวดเร็วด้วย Index และ count()

การนับจำนวนเอกสารที่มีค่าเฉพาะใน MongoDB สามารถทำได้ด้วย count() (หรือ countDocuments()) และเพิ่มประสิทธิภาพด้วย Index เนื้อหานี้สาธิตการสร้าง Index บน Field Name แล้วนับจำนวน "Chris"

สร้าง Index และข้อมูลทดสอบ

> db.demo311.ensureIndex({"Name":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

> db.demo311.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50cd01f8647eb59e562044") }

> db.demo311.insertOne({"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50cd05f8647eb59e562045") }

> db.demo311.insertOne({"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50cd06f8647eb59e562046") }

> db.demo311.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50cd0af8647eb59e562047") }

> db.demo311.insertOne({"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50cd0df8647eb59e562048") }

> db.demo311.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50cd0ff8647eb59e562049") }

แสดงข้อมูลทั้งหมด

> db.demo311.find();
{
  "_id" : ObjectId("5e50cd01f8647eb59e562044"),
  "Name" : "Chris"
}
{
  "_id" : ObjectId("5e50cd05f8647eb59e562045"),
  "Name" : "David"
}
{
  "_id" : ObjectId("5e50cd06f8647eb59e562046"),
  "Name" : "David"
}
{
  "_id" : ObjectId("5e50cd0af8647eb59e562047"),
  "Name" : "Chris"
}
{
  "_id" : ObjectId("5e50cd0df8647eb59e562048"),
  "Name" : "Bob"
}
{
  "_id" : ObjectId("5e50cd0ff8647eb59e562049"),
  "Name" : "Chris"
}

Query นับจำนวน "Chris"

> db.demo311.find({"Name":"Chris"}).count();
3

คำอธิบายและ Best Practices

  • ensureIndex() = Legacy, ใช้ createIndex() แทน: db.demo311.createIndex({Name: 1})
  • count() บน Cursor เป็น Legacy - MongoDB 4.0+ แนะนำ:
    • countDocuments({Name: "Chris"}) - นับแม่นยำ, ใช้ Index ได้, รองรับ Filter ทั้งหมด
    • estimatedDocumentCount() - เร็วมาก แต่ไม่รองรับ Filter (นับทั้ง Collection)
  • Index บน Name ช่วยให้ Query {Name: "Chris"} ใช้ Index Scan แทน Collection Scan
  • ตรวจสอบ Query Plan ด้วย .explain("executionStats")
  • Compound Index สำหรับ Query หลาย Field: createIndex({Name: 1, Age: 1})