2017-08-06 19 views
1

我試圖使用MongoDB的C#的驅動程序(2.4.4)爲了表達對下面的查詢:

db.media.aggregate({ $sample: { size: 1 }}) 

這是我到目前爲止有:

BsonDocument sample = new BsonDocument 
{ 
    { "$sample", new BsonDocument { { "size", 1 } } } 
}; 
MongoBlob mongoBlob = await _collection 
    .Aggregate() 
    .Group<MongoBlob>(sample) 
    .FirstOrDefaultAsync(); 

我不能把sample.Aggregate(AggregateOptions options = null)並把它放到.Group(...)顯然是錯誤的。也沒有任何像.Sample()方法。

請幫忙。先謝謝你。

回答

1

我相信它應該是

MongoBlob mongoBlob = await _collection 
    .Aggregate() 
    .Sample(1) 
    .FirstOrDefaultAsync(); 

如果不工作,然後讓我知道。沒有Windows系統了,現在確認

編輯(7-AUG):

原來它不是那麼簡單。示例方法在當前驅動程序中不存在。處理這個類是internal所以沒有直接的方式來繼承。因此,制定了基於反思和黑客的解決方案。在舞臺上添加舞臺,然後通過反射進行編輯。以下是我的演示代碼的工作示例:

using System; 使用MongoDB.Bson; 使用MongoDB.Driver; using System.Reflection;

namespace TestMongo 
{ 
    public static class MainClass 
    { 
     static IMongoClient _client; 
     static IMongoDatabase _database; 

     public static IAggregateFluent<BsonDocument> Sample(this IAggregateFluent<BsonDocument> agg, int count){ 
      var new_agg = agg.Skip(10); 
      var stage =new_agg.Stages[new_agg.Stages.Count-1]; 
      var newDoc = new BsonDocument { 
       { "$sample", new BsonDocument { 
         {"size", count} 
        } } 
      }; 
      stage.GetType().GetField("_document" 
      , BindingFlags.Instance | BindingFlags.NonPublic) 
       .SetValue(stage, newDoc); 
      return new_agg; 
     } 

     public static void Main(string[] args) 
     { 
      Console.WriteLine("Hello World!"); 
      _client = new MongoClient(); 
      _database = _client.GetDatabase("jobs"); 

      var col = _database.GetCollection<BsonDocument>("results"); 

      var agg = col.Aggregate().Sample(1); 

      var data = agg.FirstOrDefault(); 
      data = null; 
     } 
    } 
} 
+0

我也期待類似的東西,但沒有'.Sample()'方法。 – romaklimenko

+0

讓我檢查系統並回復給您 –

+0

@romaklimenko,檢查更新的答案 –