หากต้องการสร้างดัชนีหลายฟิลด์ ให้ใช้sureIndex() สำหรับการรวมกัน ด้วยsureIndex() เราสามารถสร้างดัชนีและแม้กระทั่งส่งผ่านหลายฟิลด์ ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo53.ensureIndex({"StudentFirstName":1,"StudentAge":1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo53.ensureIndex({"StudentFirstName":1,"StudentCountryName":1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
>db.demo53.insertOne({"StudentFirstName":"Chris","StudentAge":21,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e271431cfb11e5c34d89911")
}
>db.demo53.insertOne({"StudentFirstName":"David","StudentAge":23,"StudentCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e27143ccfb11e5c34d89912")
}
>db.demo53.insertOne({"StudentFirstName":"Mike","StudentAge":24,"StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e27144bcfb11e5c34d89913")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo53.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e271431cfb11e5c34d89911"), "StudentFirstName" : "Chris", "StudentAge" : 21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e27143ccfb11e5c34d89912"), "StudentFirstName" : "David", "StudentAge" : 23, "StudentCountryName" : "UK" }
{ "_id" : ObjectId("5e27144bcfb11e5c34d89913"), "StudentFirstName" : "Mike", "StudentAge" : 24, "StudentCountryName" : "AUS" }