2016-03-14 44 views
2

我想從數據庫中使用Sample()方法獲得一些隨機項目。我更新到最新版本的驅動程序,並複製鏈接示例中的使用語句。然而,有些東西沒有用,我希望這是我的一個簡單的錯誤。所有的相關信息是在下面的圖片:使用MongoDb C#驅動程序的示例難(012)

enter image description here

編輯:

格雷格,我讀了聚集文檔here和原始數據庫方法doc here,但我還是不明白這一點。最後兩行是我的嘗試,我之前從未使用過聚合:

  var mongoCollection = GetMongoCollection<BsonDocument>(collectionName); 
      long[] locationIds = new long[] { 1, 2, 3, 4, 5 }; 
      var locationsArray = new BsonArray(); 
      foreach (long l in locationIds) { locationsArray.Add(l); }; 
      FilterDefinition<BsonDocument> sampleFilter = Builders<BsonDocument>.Filter.In("LocationId", locationsArray); 
      var findSomething = mongoCollection.Find(sampleFilter); //this works, the two attempts below don't. 
      var aggregateSomething = mongoCollection.Aggregate(sampleFilter).Sample(25); 
      var aggregateSomething2 = mongoCollection.Aggregate().Match(sampleFilter).Sample(25); 

回答

4

樣本僅適用於聚合。你需要從Aggregate開始,而不是Find。我相信它也可以在Linq中找到。

更新: 看起來我們沒有具體的方法。但是,您可以使用AppendStage方法。

mongoCollection.Aggregate(sampleFilter) 
       .AppendStage<BsonDocument>("{ $sample: { size: 3 } }"); 
+0

克雷格,你有什麼機會給我一個例子嗎?我試圖尋找你使用的「CreateQuery()」函數,希望它有一個聚合的例子,但我沒有找到它。 – VSO