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

การสร้างดัชนี (Index) ในคอลเล็กชัน MongoDB


เพื่อสร้างดัชนี ให้ใช้ createIndex() ใน MongoDB มาสร้างคอลเล็กชันพร้อมเอกสารกันเถอะ

> db.demo702.createIndex({"details.id":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo702.insertOne({
    "details" : [
        {
            id:101,
            studentInfo:{
                "StudentName" : "Chris",
                "StudentAge" : 23,
            }
        },
        {
            id: 102,
            studentInfo:{
                "StudentName" : "Robert",
                "StudentAge" : 20,
            }
        }
    ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6ea3b551299a9f98c93b3") }

แสดงเอกสารทั้งหมดด้วยเมธอด find()

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

ผลลัพธ์ที่ได้

{ "_id" : ObjectId("5ea6ea3b551299a9f98c93b3"), "details" : [ { "id" : 101, "studentInfo" : { "StudentName" : "Chris", "StudentAge" : 23 } }, { "id" : 102, "studentInfo" : { "StudentName" : "Robert", "StudentAge" : 20 } } ] }