2016-01-16 30 views
1

我有一個BsonDocuments集合,每個都有一個名爲「engagement」(這是一個數字)的字段和一個名爲「color」的字段。我希望所有BsonDocuments的「color」=「blue」的總成本。MongoDB驅動程序C#試圖做基本的數學,但不明白聚合

所以從我學到了什麼是我需要做這樣的事情遠:

  var collection = db.GetCollection<BsonDocument>("collectionName"); 

      var match = new BsonDocument 
      { 
       { 
        "$match", 
        new BsonDocument 
         { 
          {"sentiment", "positive"} 
         } 
       } 
      }; 

      var group = new BsonDocument 
      { 
       { "$group", 
        new BsonDocument 
         { 
          { 
           "Sum", new BsonDocument 
              { 
               { 
                "$sum", "$engagement" 
               } 
              } 
          } 
         } 
       } 
      }; 

      var pipeline = new[] { match, group }; 
      var result = collection.Aggregate(pipeline); 

我已經得到有關的聚合方法類型方法的參數錯誤不能從使用推斷。

簡而言之,我想知道如何使用Aggregate Framework執行簡單的數學運算。在這個例子中,我試圖從集合中的所有BsonDocuments中總結交互字段的所有值。儘可能使用Builder函數會很好,但手動創建的BsonDocument也可以。

感謝您的時間

回答

0

當您使用$group,你需要告訴聚合框架由哪些字段要組。您可以在_id字段中爲組對象執行此操作。另外,如果您想要簡單的文檔計數,則需要使用{ $sum : 1 }來計算每個文檔一個。如果您使用字段名稱,則告訴聚合將該字段的值解釋爲數字並將其相加。

在MongoDB中的shell語法:

{ $group: { 
    _id: "$engagement", 
    Sum: { $sum: 1 } 
}} 

翻譯成C#(未經測試!):

{ "$group", new BsonDocument 
    { 
     { "_id", "$engagement" }, 
     { "Sum", new BsonDocument 
      { 
       { 
        "$sum", 1 
       } 
      } 
     } 
    } 
} 
+0

感謝您的答覆,我現在好理解的總和。 我仍然收到有關類型方法的錯誤,因爲無法從我聲明結果的代碼行中的用法推斷出Aggregate方法的參數。有什麼想法可能是關於什麼? –

相關問題