Để hiển thị các chỉ mục của một tập hợp, bạn có thể sử dụng getIndexes (). Cú pháp như sau -
db.yourCollectionName.getIndexes();
Để hiểu khái niệm, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -
> db.indexDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f7c4f2f684a30fbdfd599")
}
> db.indexDemo.insertOne({"StudentName":"Mike","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f7c552f684a30fbdfd59a")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -
> db.indexDemo.insertOne({"StudentName":"Carol","StudentAge":20}); Sau đây là kết quả -
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f7c5e2f684a30fbdfd59b")
}
> db.indexDemo.find().pretty();
{
"_id" : ObjectId("5c8f7c4f2f684a30fbdfd599"),
"StudentName" : "Larry",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c8f7c552f684a30fbdfd59a"),
"StudentName" : "Mike",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c8f7c5e2f684a30fbdfd59b"),
"StudentName" : "Carol",
"StudentAge" : 20
} Đây là truy vấn để tạo chỉ mục -
> db.indexDemo.createIndex({"StudentName":-1,"StudentAge":-1}); Sau đây là kết quả:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
} Đây là truy vấn để hiển thị các chỉ mục của một bộ sưu tập. Tên bộ sưu tập là “indexDemo” -
> db.indexDemo.getIndexes();
Sau đây là kết quả -
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.indexDemo"
},
{
"v" : 2,
"key" : {
"StudentName" : -1
},
"name" : "StudentName_-1",
"ns" : "test.indexDemo"
},
{
"v" : 2,
"key" : {
"StudentName" : -1,
"StudentAge" : -1
},
"name" : "StudentName_-1_StudentAge_-1",
"ns" : "test.indexDemo"
}
]