如何在 MongoDB 中顯示集合的索引?


若要顯示集合的索引,可以使用 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() 方法從集合中顯示所有文件。查詢如下 −

> 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"
   }
]

更新於: 30-Jul-2019

296 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.