使用LINQ的MongoDB C#聚合 [英] MongoDB C# Aggregation with LINQ

查看:207
本文介绍了使用LINQ的MongoDB C#聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下字段的mongo对象:

I have a mongo object with these fields:

DateTime TimeStamp;
float    Value;

如何使用LINQ在C#中获得聚合管道,以获取最小值,最大值和

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.

推荐答案

您可以使用LINQ语法被翻译成Aggregation Framework的语法。假设您具有以下 Model 类:

You can use LINQ syntax which gets translated into Aggregation Framework's syntax. Assuming you have following Model class:

public class Model
{
    public DateTime Timestamp { get; set; }
    public float Value { get; set; }
}

您可以使用 where 指定时间戳范围,然后使用 group null 作为分组键。 MongoDB驱动程序将从匿名翻译出 Min Max Average 键入 $ max $ min $ avg 聚合框架语法

you can use where to specify timestamp range and then use group with null as grouping key. MongoDB driver will translate Min, Max and Average from anonymous type into $max, $min and $avg from Aggregation Framework syntax

var q = from doc in Col.AsQueryable()
        where doc.Timestamp > DateTime.Now.AddDays(-3)
        where doc.Timestamp < DateTime.Now.AddDays(3)
        group doc by (Model)null into gr
        select new
        {
            Avg = (double)gr.Average(x => x.Value),
            Min = gr.Min(x => x.Value),
            Max = gr.Max(x => x.Value)
        };

var result = q.First();

MongoDB驱动程序支持的累加器列表可以找到此处

List of accumulators supported by MongoDB driver can be found here.

编辑:(Model)null 是必需的,因为必须将查询转换为 $ group _id 设置为 null 文档),因为您希望通过汇总获得一个结果。仅出于C#编译器的目的就需要强制转换,因为doc的类型为 Model

the (Model)null is required because the query has to be transformed to $group with _id set to null (docs) since you want to get one result with aggregates. Casting is required just for C# compiler purpose as doc is of type Model.

这篇关于使用LINQ的MongoDB C#聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆