MongoDB “count()” 非常慢。我們如何解決呢?


可以使用 ensureIndex() 來提升 MongoDB 中 count() 方法的效能。為了理解這個概念,我們使用文件建立集合。建立帶文件集合的查詢如下 −

> db.countPerformanceDemo.insertOne({"StudentName":"John","StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ebcf82f684a30fbdfd55f")
}
> db.countPerformanceDemo.insertOne({"StudentName":"Mike","StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ebd042f684a30fbdfd560")
}
> db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ebd112f684a30fbdfd561")
}
> db.countPerformanceDemo.insertOne({"StudentName":"Carol","StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ebd1a2f684a30fbdfd562")
}
> db.countPerformanceDemo.insertOne({"StudentName":"Bob","StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ebd212f684a30fbdfd563")
}

> db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ebd9a2f684a30fbdfd564")
}
> db.countPerformanceDemo.insertOne({"StudentName":"David","StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ebd9e2f684a30fbdfd565")
}

透過使用 find() 方法顯示集合中的所有文件。查詢如下 −

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

以下是輸出 −

{
   "_id" : ObjectId("5c8ebcf82f684a30fbdfd55f"),
   "StudentName" : "John",
   "StudentCountryName" : "US"
}
{
   "_id" : ObjectId("5c8ebd042f684a30fbdfd560"),
   "StudentName" : "Mike",
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5c8ebd112f684a30fbdfd561"),
   "StudentName" : "David",
   "StudentCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c8ebd1a2f684a30fbdfd562"),
   "StudentName" : "Carol",
   "StudentCountryName" : "US"
}
{
   "_id" : ObjectId("5c8ebd212f684a30fbdfd563"),
   "StudentName" : "Bob",
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5c8ebd9a2f684a30fbdfd564"),
   "StudentName" : "David",
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5c8ebd9e2f684a30fbdfd565"),
   "StudentName" : "David",
   "StudentCountryName" : "US"
}

這裡是對 count() 進行高效能形式的查詢 −

> db.countPerformanceDemo.ensureIndex({"StudentName":1});
{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

現在,實現 count() 方法。它計算 StudentName 為”David”的記錄

> db.countPerformanceDemo.find({"StudentName":"David"}).count();

以下是輸出 −

3

更新日期: 2019 年 7 月 30 日

超過 1K 的瀏覽量

開啟你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.