簡體   English   中英

嘗試從MongoDB存儲庫中跳過和獲取數據時,溢出排序階段緩沖了數據的使用

[英]Overflow sort stage buffered data usage when trying to skip and take from MongoDB repository

我有一個啟用REST和ODATA的經典Web API控制器,它調用基於MongoDB的存儲庫模式實現。

我不斷

溢出排序階段緩沖的數據使用量33556193字節超過了內部限制33554432字節

當我嘗試跳過前12010年以上的記錄並獲得前10名時

?$skip=12020&$top=10&$orderby=Serial

經過一些搜索后,我嘗試在Serial上實現一個索引,例如

private void GetCollection() //is like DBSet of some entity
{
  _collection = _dbContext.Database
     .GetCollection<TEntity>(typeof(TEntity).Name);
  Type typeParameterType = typeof(TEntity);
  if (typeParameterType.Name == "StoreCommand")
    if (_collection.IndexExists("Serial") == false)
      _collection.CreateIndex(IndexKeys<StoreCommand>.Ascending(_ => _.Serial));
}

我的存儲庫實現是這樣的。

    public class MongoDbRepository<TEntity> :
    IRepository<TEntity> where
        TEntity : EntityBase
{
    private MongoCollection<TEntity> _collection;

    private SNDbContext _dbContext;
    public MongoDbRepository(SNDbContext dbContext)
    {
        _dbContext = dbContext;
        GetCollection();
    }
    private void GetCollection()
    {
        _collection = _dbContext.Database
            .GetCollection<TEntity>(typeof(TEntity).Name);
    }
    public IQueryable<TEntity> GetAll()
    {
        return _collection.AsQueryable(); 
    }//............And other functions after this

}

來自服務層的呼叫是這樣的

 IQueryable<StoreCommand> GetAllStoreCommands() 
  {
     return _uow.StoreCommands.GetAll(); 
   } 

其中SNDbContext具有與使用MongoClient和連接字符串獲取數據庫有關的所有代碼。

問題在於,在存儲庫實現中(未顯示),您將從MongoDB中獲取所有數據,然后將所有這些數據存儲在緩沖區中並在內存中進行排序以允許跳過和獲取。

您要做的是通過以下兩種方式之一來修改存儲庫:

  • 返回一個純可查詢的內容,以便您可以組成其余的查詢,並仍然使其在MongoDB引擎上執行
  • 直接公開一個方法,該方法接收要跳過和采用的參數,並進行查詢以直接在數據庫中執行這些參數。

您可以使用游標實現它,如下所示:

var collection = db.GetCollection<YourType>("yourtype");
var sort = SortBy<YourType>
            .Ascending(p => p.YourProperty1)
            .Descending(p => p.YourProperty2);
MongoCursor<YourType> cursor = collection
  .FindAll()
  .SetSortOrder(sort)
  .SetSkip(12010)
  .SetLimit(10);

如果您迭代此游標,則根本不會出現任何問題。

您還可以定義和執行SelectQuery ,並指定SkipTake值。 請參閱文檔: SelectQuery屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM