【发布时间】:2015-02-03 14:54:13
【问题描述】:
我们正在使用 C# MongoDB 驱动程序,我们希望对时间戳的日期部分进行分组,并获取该日期的平均值。问题是我们无法使用构建器为组找到正确的合成器。
这段代码显示了如何使用 BSON 文档创建组,但我们发现合成器读起来不清晰而且非常混乱!因此正在寻找正确的构建器合成器。
我们希望使用 Builders,因为它在 C# 中的类型更多,然后在管道中使用带有 BsonDocuments 的方法。这是一个代码 sn-p,前 3 个操作在其中起作用,但我们找不到 GroupBy。
DateTime from = new DateTime(2014, 12, 2);
DateTime to = new DateTime(2014, 12, 4);
var id = "37d163c0-44cc-4907-94cf-1e26b5eec911";
var grp = new BsonDocument
{
{
//Sort the documents into groups
"$group",
new BsonDocument
{
//Make the unique identifier for the group a BSON element consisting
// of a field named Car.
// Set its value to that of the Cars field
// The Cars field is nolonger an array because it has now been unwound
//{ "_id", new BsonDocument { { "Date", "$Date" } } },
{
"_id",new BsonDocument{ new BsonDocument("year",new BsonDocument ("$year","$Date")),
new BsonDocument("month",new BsonDocument ("$month","$Date")),
new BsonDocument("day",new BsonDocument ("$dayOfMonth","$Date"))
}
},
{
//Add a field named Owners
"avgAmount",
new BsonDocument
{
{ "$avg" ,"$Value"}
}
}
}
}
};
AggregateArgs aggregateArgs = new AggregateArgs()
{
Pipeline = new[]
{
new BsonDocument("$match", Query<Reading>.EQ(c => c.SensorId, id).ToBsonDocument())
, new BsonDocument("$match", Query<Reading>.LTE(c => c.Date, to).ToBsonDocument())
, new BsonDocument("$match", Query<Reading>.GTE(c => c.Date, from).ToBsonDocument())
, grp
//, new BsonDocument("$group",GroupBy<Reading>.Keys(c=> c.Date).ToBsonDocument())
}
};
IEnumerable<BsonDocument> documents = collection.Aggregate(aggregateArgs);
感谢所有帮助,我们已经查看了论坛上的类似问题,但找不到正确的工作解决方案,question 1 或 question 2。
【问题讨论】:
-
在link找到很多有用的信息