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

MongoDB: ใช้ดัชนีสำหรับ Subdocument ที่ไม่รู้ชื่อฟิลด์ล่วงหน้า


แนวคิด: Indexing บน Key/Value แบบ Dynamic

สามารถสร้างดัชนีบน properties.k สำหรับ key และ properties.v สำหรับ value ได้ ใช้ร่วมกับ ensureIndex()

สร้างคอลเลกชันตัวอย่าง

> db.demo274.insertOne({
  "details": [
    {StudentFirstName:"Chris",StudentLastName:"Brown"},
    {StudentFirstName:"David",StudentLastName:"Miller"},
    {StudentFirstName:"John",StudentLastName:"Smith"},
    {StudentFirstName:"John",StudentLastName:"Doe"}
  ]
});
{ "acknowledged": true, "insertedId": ObjectId("5e48de35dd099650a5401a42") }

แสดงข้อมูล

> db.demo274.find().pretty();
{ "_id": ObjectId("5e48de35dd099650a5401a42"), "details": [ { "StudentFirstName": "Chris", "StudentLastName": "Brown" }, { "StudentFirstName": "David", "StudentLastName": "Miller" }, { "StudentFirstName": "John", "StudentLastName": "Smith" }, { "StudentFirstName": "John", "StudentLastName": "Doe" } ] }

สร้างดัชนี Compound บนฟิลด์ใน Subdocument

> db.demo274.ensureIndex({"details.StudentFirstName": 1, "details.StudentLastName": 1});

ผลลัพธ์: สร้างดัชนีสำเร็จ

{ "createdCollectionAutomatically": false, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }