I have a mongo object with these fields:
DateTime TimeStamp;
float Value;
How can I get the aggregation pipeline, in C#, with LINQ, to get the minimum, maximum and average of Value over a specific timestamp range?
I have seen a few aggregation examples, but I don't quite get it. Having an example on a simple case like this would certainly (hopefully) make me understand it.
The aggregation for this is done in two steps:
$match
- Retrieve documents withTimeStamp
value between some definedminDate
andmaxDate
.$group
- Group on null. This will put all documents in a single group so we can apply an accumulator function across everything from the step 1 $match. The accumulator functions you're looking for are$min
,$max
, and$avg
.You can use LINQ syntax which gets translated into Aggregation Framework's syntax. Assuming you have following
Model
class:you can use
where
to specify timestamp range and then usegroup
withnull
as grouping key. MongoDB driver will translateMin
,Max
andAverage
from anonymous type into$max
,$min
and$avg
from Aggregation Framework syntaxList of accumulators supported by MongoDB driver can be found here.
EDIT: the
(Model)null
is required because the query has to be transformed to$group
with_id
set tonull
(docs) since you want to get one result with aggregates. Casting is required just for C# compiler purpose as doc is of typeModel
.