C#のMongoDBドライバでmongodbの最新バージョンを使用しています。私は少しの例を作りました。それは私の問題を説明するはずです。私の目標は、条件付きCount()、条件付きFirst()またはAverage()をフィルタ付きで作成することではありません。それは動作しません。c#とmongodb:フィルタ付き集計
この問題に対する最良の解決策は何でしょうか。任意のヒントありがとう
class MealDocument
{
public string name { get; set; }
public DateTime time { get; set; }
public Type type { get; set; }
public double calorie { get; set; }
public enum Type { breakfast, launch, dinner }
}
class MealAnalysis
{
public string name { get; set; }
public int numberOfBreakfast { get; set; }
public DateTime firstLaunch { get; set; }
public double averageDinnerCalorie { get; set; }
}
public void Test()
{
var collection = Database.GetCollection<MealDocument>("meal_test");
collection.InsertMany(new MealDocument[] {
new MealDocument { name = "Thomas", type = MealDocument.Type.breakfast, calorie = 100, time = new DateTime(2017,8,1) },
new MealDocument { name = "Thomas", type = MealDocument.Type.breakfast, calorie = 100, time = new DateTime(2017,8,2) },
new MealDocument { name = "Thomas", type = MealDocument.Type.launch, calorie = 800, time = new DateTime(2017,8,3) },
new MealDocument { name = "Thomas", type = MealDocument.Type.dinner, calorie = 2000, time = new DateTime(2017,8,4) },
new MealDocument { name = "Peter", type = MealDocument.Type.breakfast, calorie = 100, time = new DateTime(2017,8,5) },
new MealDocument { name = "Peter", type = MealDocument.Type.launch, calorie = 500, time = new DateTime(2017,8,6) },
new MealDocument { name = "Peter", type = MealDocument.Type.dinner, calorie = 800, time = new DateTime(2017,8,7) },
new MealDocument { name = "Paul", type = MealDocument.Type.breakfast, calorie = 200, time = new DateTime(2017,8,8) },
new MealDocument { name = "Paul", type = MealDocument.Type.launch, calorie = 600, time = new DateTime(2017,8,9) },
new MealDocument { name = "Paul", type = MealDocument.Type.launch, calorie = 700, time = new DateTime(2017,8,10) },
new MealDocument { name = "Paul", type = MealDocument.Type.dinner, calorie = 1200, time = new DateTime(2017,8,11) }
});
var analysis = collection.Aggregate()
.Group(
doc => doc.name,
group => new MealAnalysis
{
name = group.Key,
// !!!! The condition in the Count() gets ignored
numberOfBreakfast = group.Count(m => m.type == MealDocument.Type.breakfast),
// !!!! Exception --> Not supported
averageDinnerCalorie = group.Where(m => m.type == MealDocument.Type.dinner).Average(m => m.calorie),
// !!!! Exception --> Not supported
firstLaunch = group.First(m => m.type == MealDocument.Type.launch).time
}
);
var query = analysis.ToString();
var result = analysis.ToList();
}
私は** lunch ** break =)でお手伝いします。プロジェクトの一部が欠けています。この投稿はhttps://stackoverflow.com/questions/27315852/mongodb-driver-builders-how-to-group-and-get-averageに役立つかもしれません。私はカップルの時間にあなたに戻ってきます。 – BOR4