[英]MongoDb C# Driver - Get item by indexed field very slow
在小型本地數據庫上獲取過濾數據時,我遇到了性能問題。 我減少了代碼(如下所示)以重現該問題。 輸出約為2000ms。
一些其他信息:
碼:
public class UnitTest1
{
public void TestMethod2()
{
Stopwatch sw = new Stopwatch();
sw.Start();
new BaseRepository<TickerData>().GetById("5731d39062deb83134772e77");
sw.Stop();
Debug.Write(sw.Elapsed.TotalMilliseconds);
}
}
public class BaseRepository<T> : MongoBase where T : BaseEntity
{
MongoDatabase DataBase { get; set; }
protected IQueryable<T> Collection { get; set; }
MongoCollection<BsonDocument> mCollection { get; set; }
public BaseRepository()
{
DataBase = Server.GetDatabase("TradingBot");
mCollection = DataBase.GetCollection<BsonDocument>(typeof(T).Name);
Collection = mCollection.AsQueryable<T>();
}
public T GetById(string ID)
{
return Collection.Single(i => i.Id.ToString() == ID);
}
}
更新:根據@rnofenko提出的建議(請參閱評論)取得了很大的進步,但似乎仍然很慢?
這是一個棘手的時刻。 您從System.Linq調用擴展方法Single 。 實際上,您是從數據庫加載整個集合,然后在應用程序中按ID選擇。
相反,您需要使用MongoDB擴展方法-MongoDB.Driver.Linq中的SingleAsync 。
public async Task<T> GetById(string id)
{
return await Collection.SingleAsync(x => x.Id == new ObjectId(id));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.