Để hiển thị tất cả indexes của một collection trong MongoDB, bạn sử dụng phương thức getIndexes().
Cú pháp
db.yourCollectionName.getIndexes();
Ví dụ minh họa
Tạo collection và dữ liệu
> db.indexDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8f7c4f2f684a30fbdfd599") }
> db.indexDemo.insertOne({"StudentName":"Mike","StudentAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8f7c552f684a30fbdfd59a") }
> db.indexDemo.insertOne({"StudentName":"Carol","StudentAge":20});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8f7c5e2f684a30fbdfd59b") }
Xem dữ liệu
> 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
}
Tạo index compound
> db.indexDemo.createIndex({"StudentName":-1,"StudentAge":-1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
Hiển thị tất cả indexes
> db.indexDemo.getIndexes();
[
{
"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"
}
]
Giải thích output
| Trường | Ý nghĩa |
v | Version của index format |
key | Trường và thứ tự index (1=tăng, -1=giảm) |
name | Tên index (tự động sinh hoặc custom) |
ns | Namespace: database.collection |
Các lệnh index hữu ích khác
| Lệnh | Mục đích |
getIndexes() | Liệt kê tất cả indexes |
createIndex(keys, options) | Tạo index mới |
dropIndex(name) | Xóa index theo tên |
dropIndexes() | Xóa tất cả indexes (trừ _id) |
totalIndexSize() | Kích thước toàn bộ indexes (bytes) |
stats() | Thống kê collection bao gồm index stats |
Tạo index với tên tùy chỉnh
db.indexDemo.createIndex(
{"StudentName": 1},
{name: "idx_student_name_asc"}
);