為什麼 MongoDB 查詢記錄需要花費太多時間?


在這種情況下,使用特定欄位的索引概念。讓我們先使用文件建立一個集合。在這裡,我們還使用 createIndex() 建立了索引 −

> db.decreasetimeusingindex.createIndex({"StudentName":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.decreasetimeusingindex.insertOne({"StudentName":"John Smith","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e03960af5e889d7a51994ff")
}
> db.decreasetimeusingindex.insertOne({"StudentName":"John Doe","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e039611f5e889d7a5199500")
}
> db.decreasetimeusingindex.insertOne({"StudentName":"Adam Smith","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e03961df5e889d7a5199501")
}

以下是使用 find() 方法從集合中顯示所有文件的查詢 −

> db.decreasetimeusingindex.find().pretty();

這將生成以下輸出 −

{
   "_id" : ObjectId("5e03960af5e889d7a51994ff"),
   "StudentName" : "John Smith",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5e039611f5e889d7a5199500"),
   "StudentName" : "John Doe",
   "StudentAge" : 24
}
{
   "_id" : ObjectId("5e03961df5e889d7a5199501"),
   "StudentName" : "Adam Smith",
   "StudentAge" : 22
}

以下是查詢特定記錄的查詢 −

> db.decreasetimeusingindex.find({"StudentName":"Adam Smith"});

這將生成以下輸出 −

{ "_id" : ObjectId("5e03961df5e889d7a5199501"), "StudentName" : "Adam Smith", "StudentAge" : 22 }

更新於: 2020 年 3 月 27 日

191 次瀏覽

助力你的 事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.