MongoDB的结果为聚集集合() [英] MongoDB result set for Aggregate()
问题描述
我开始了与蒙戈客户做一些漂亮的查询和aggretations ..但现在,我想在.NET / C#中使用它,我知道我不能简单地运行查询的文本字段..
I started out with Mongo client doing some nifty queries and aggretations.. but now that I want to use it in .NET/C#, I see that I can't simply run the query as text field..
此外,诉诸建立一个聚合管道,并运行collection.Aggregate()函数之后,我得到一个结果集,但我不知道如何遍历它..
Furthermore, after resorting to building an Aggregation Pipeline, and running the collection.Aggregate() function, I'm getting a result set, but I have no idea how to traverse it..
谁能帮助指导我在这里?
Can anyone help guide me here?
下面是我的code:
var coll = db.GetCollection("animals");
var match = new BsonDocument {
{ "$match", new BsonDocument {{"category","cats"}} }
};
var group = new BsonDocument{
{
"$group", new BsonDocument{
{"_id", "$species"},
{"AvgWeight", new BsonDocument{{"$avg", "$weight"}}} }
}
};
var sort = new BsonDocument{{"$sort", new BsonDocument{{"AvgWeight", -1}}}};
var pipeline = new[] { match, group, sort };
var args = new AggregateArgs { Pipeline = pipeline };
var res = coll.Aggregate(args);
foreach (var obj in res)
{
// WHAT TO DO HERE??
}
另外,我应该说我是一个有点生疏用C#/ ASP.NET / MVC所以任何简化有关将大大AP preciated。
Also, I should say that I'm a little rusty with C# / ASP.NET / MVC so any room for simplification would be much appreciated.
推荐答案
您的结果是IEnumerable的BsonDocument,你可以将它们序列化使用BSonSerializer C#对象。而这code片段只是将它们写入到控制台,但你可以看到您键入对象
Your result is IEnumerable of BsonDocument, you can Serialize them to C# objects using the BSonSerializer. And this code snippet just writes them to your console, but you can see that you have typed objects
List<Average> returnValue = new List<Average>();
returnValue.AddRange(documents.Select(x=> BsonSerializer.Deserialize<Average>(x)));
foreach (var obj in returnValue)
{
Console.WriteLine("Species {0}, avg weight: {1}",returnValue._Id,returnValue.AvgWeight);
}
再有一个叫平均班级,其属性名在BSonDocument如果要重命名,然后(因为_id是不是在关于命名约定C#条款这么好)相匹配的名称,你可以添加一个$项目BsonDocument你的管道。
And then have a class called Average, where the property name match the names in the BSonDocument, if you want to rename then (because _Id is not so nice in c# terms concerning naming conventions), you can add a $project BsonDocument to your pipeline.
public class Average
{
public string _Id { get; set; }
public Double AvgWeight {get; set; }
}
$项目样本(在管道添加此之前的排序
$project sample (add this in your pipeline just before sort
var project = new BsonDocument
{
{
"$project",
new BsonDocument
{
{"_id", 0},
{"Species","$_id"},
{"AvgWeight", "$AvgWeight"},
}
}
};
这篇关于MongoDB的结果为聚集集合()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!