We are using the C # MongoDB driver, and we would like to group by date the timestamp and get the average for that date. The problem is that we cannot find the correct syntax for the group using builders.
This code shows how a group is created with BSON documents, but we find that the syntax is not readable and very confusing! So we were looking for the correct linker syntax.
We would like to use Builders because it is more typed in C # and then uses the method with BsonDocuments in the pipeline. Here is a piece of code in which the first 3 operations work, but we cannot recognize 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
{
{
"$group",
new BsonDocument
{
{
"_id",new BsonDocument{ new BsonDocument("year",new BsonDocument ("$year","$Date")),
new BsonDocument("month",new BsonDocument ("$month","$Date")),
new BsonDocument("day",new BsonDocument ("$dayOfMonth","$Date"))
}
},
{
"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
}
};
IEnumerable<BsonDocument> documents = collection.Aggregate(aggregateArgs);
, , , 1 2.