MongoDB Aggregation集約操作

2478 ワード

MongoDB Aggregation
最近、製品のバックグラウンド管理をしている時、クエリーのデータ量が比較的大きい時、MongoDBは間違いを報告して、クエリーの時にソート機能を使ったため、
Sort operation used more than the maximum 33554432 bytes of RAM.
Add an index, or specify a smaller limit..

公式文書の説明によると、Sortはメモリ内での操作であり、使用するメモリは32 MBを超えてはならず、32 MBを超えるとエラーが報告される.Indexインデックスを増やすことをお勧めしますが、インデックスを増やすとストレージ量が増加し、書き込み速度にも影響します.Aggregation集約を使用して、大量のデータのクエリーとソートを操作できます.
  • Aggregation Pipeline操作の制限MongoDB 2.6以降、Aggregation Pipeline操作の最大メモリ制限は100 MBであり、100 MBを超えるとエラーも報告されます.Aggregationを使用する場合、大量のデータを処理する場合は、allowDiskUseパラメータを使用します.このパラメータは、処理するデータを一時ファイルに
  • に書き込むことができます.
    Aggregationオペレーション
    db.collection.aggregate( [ {  }, ... ] )
    
    $match
    $sort
    $limit
    ....
    

    具体的なstageに関する文は、公式にサポートされている式aggregate pipeline operationを参照してください.
    Aggregation C# Driver
    // connectionString="mongodb://127.0.0.1:27017"
    
    var client = new MongoClient(connectionString);
    IMongoDatabase _db = client.GetDatabase(dbName);
    var collection = GetCollection(collectionName)
    
    
    IList stages = new List();
    
    //  
    string f = "{ $or: [ { _id: { $eq:" + "\"" + query + "\"} }, { sn: { $eq: " + "\"" + query + "\" } } ] }";
    string idMatch = "{ $match: " + f + "}";
    PipelineStageDefinition queryPipline = new JsonPipelineStageDefinition(idMatch);
    
    stages.Add(queryPipline);
    
    //  
    string sortPipeline = "{$sort:{time:-1}}";
    PipelineStageDefinition sortPipline = new JsonPipelineStageDefinition(sortPipeline);
    
    stages.Add(sortPipline);
    
    //  
    string skipPiple = "{$skip:" + page * 10 + "}";
    string limitPiple = "{$limit:" + 10 + "}";
    PipelineStageDefinition skipPipline = new JsonPipelineStageDefinition(skipPiple);
    PipelineStageDefinition limitPipline = new JsonPipelineStageDefinition(limitPiple);
    
    stages.Add(skipPipline);
    stages.Add(limitPipline);
    
    PipelineDefinition pipe = new PipelineStagePipelineDefinition(stages);
    
    
    AggregateOptions options = new AggregateOptions();
    options.AllowDiskUse = true;
    
    collection.Aggregate(pipeline, options).ToList();