为了显示集合的索引,您可以使用getIndexes()
。语法如下-
db.yourCollectionName.getIndexes();
为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.indexDemo.insertOne({"StudentName":"Larry","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f7c4f2f684a30fbdfd599") } > db.indexDemo.insertOne({"StudentName":"Mike","StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f7c552f684a30fbdfd59a") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.indexDemo.insertOne({"StudentName":"Carol","StudentAge":20});
以下是输出-
{ "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 }
这是创建索引的查询-
> db.indexDemo.createIndex({"StudentName":-1,"StudentAge":-1});
以下是输出:
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 }
这是显示集合索引的查询。集合名称是“ indexDemo”-
> 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" } ]