2016-11-09 81 views
1

dbsample:MongoDB中得到平均每個arrayelement

var doc1= new BsonDocument 
{ 
    { "line", "a" }, 
    { "size", new BsonArray { 2 } } 
}; 
var doc2= new BsonDocument 
{ 
    { "line", "xx" }, 
    { "size", new BsonArray { 5, 3, 8} } 
}; 
var doc3= new BsonDocument 
{ 
    { "line", "xx" }, 
    { "size", new BsonArray { 1, 10, 8} } 
}; 

我想按行BsonDocument,得到各行的數量和每BsonArrayElement的魅力。分組和計數作品,但我怎樣才能得到每個BsonArrayElement的平均值? BsonArray的長度在不同的行之間有所不同。我想

var filterBuilder = Builders<BsonDocument>.Filter; 
var aggregate = collection.Aggregate().Group(new BsonDocument { { "_id", "$line" }, { "count", new BsonDocument("$sum", 1) } }); 
foreach (var document in aggregate.ToEnumerable()) 
{ 
    Console.WriteLine(document); 
} 

輸出:

{ "_id" : "xx", "count" : 2, "avg" : [3, 6.5, 8] } 
{ "_id" : "a", "count" : 1, "avg" : [2]} 

回答

0

要獲得期望的結果,你需要構建和運行聚合管道具有以下運營商:

db.collection.aggregate([ 
    { 
     "$group": { 
      "_id": "$line", 
      "count": { "$sum": 1 }, 
      "doc": { "$push": "$$ROOT" } 
     } 
    }, 
    { "$unwind": "$doc" }, 
    { 
     "$unwind": { 
      "path": "$doc.size", 
      "includeArrayIndex": "arrayIndex" 
     } 
    }, 
    { 
     "$group": { 
      "_id": { 
       "line": "$doc.line", 
       "idx": "$arrayIndex" 
      }, 
      "avg": { "$avg": "$doc.size" }, 
      "count": { "$first": "$count" }    
     } 
    }, 
    { "$sort": { "_id.idx": 1 } }, 
    { 
     "$group": { 
      "_id": "$_id.line", 
      "count": { "$first": "$count" }, 
      "avg": { "$push": "$avg" } 
     } 
    }  
]) 

C#實現(未測試):

var result = await collection.Aggregate() 
    .Group(new BsonDocument { 
     { "_id", "$line" }, 
     { "count", new BsonDocument("$sum", 1) }, 
     { "doc", new BsonDocument("$push", "$$ROOT") }  
    }) 
    .Unwind(x => x.doc) 
    .Unwind(new BsonDocument { 
     { "path", "$doc.size" }, 
     { "includeArrayIndex", "arrayIndex" } 
    }) 
    .Group(new BsonDocument { 
     { "_id", new BsonDocument { 
      { "line", "$doc.line" }, 
      { "idx", "$arrayIndex" } 
     } }, 
     { "avg", new BsonDocument("$avg", "$doc.size") }, 
     { "count", new BsonDocument("$first", "$count") }  
    }) 
    .Sort(new BsonDocument("_id.idx", 1)) 
    .Group(new BsonDocument { 
     { "_id", "$_id.line" }, 
     { "count", new BsonDocument("$first", "$count") }, 
     { "avg", new BsonDocument("$push", "$avg") }, 
    }) 
    .ToListAsync(); 
+0

謝謝。代碼在shell中工作,但在C#中我得到一個錯誤「'BsonDocument'不包含'doc'的定義,並且沒有擴展方法'doc'接受類型'BsonDocument'的第一個參數可以被發現(你是否缺少一個使用指令或程序集引用?)「 – seeberg

+0

正如我在答案中提到的,我沒有測試過這個。當我有機會的時候,我會但是你可能需要調試管道,特別是在這個可能需要重構的'.Unwind(x => x.doc)'步驟。 – chridam

+0

我無法得到它的工作:( – seeberg