We are using the C# MongoDB driver, and we would like to group on the Date part of a timestamp and get the average for that date. The problem is that we can't find the correct synthax for the group using the builders.
This code shows how the group is made with BSON documents, but we find that synthax not clear to read and very confusing ! So were are looking for the correct builder synthax.
We would like to use the Builders because it is more typed in C# then using the method with BsonDocuments in a pipeline. Here is a code snippet, where the first 3 operations work, but we can't find out 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);
All help is appreciated, we already looked in simular questions on the forum, but can't find a correct working solution, question 1 or question 2.
See Question&Answers more detail:
os