MongoDB使用C#驱动程序和时间间隔LINQ

时间:2018-01-25 12:53:25

标签: c# mongodb linq aggregation-framework

使用C#MongoDB驱动程序时 - 是否可以使用LINQ创建一个聚合,创建一个按时间间隔对结果进行分组的结果 - 如下所示:

pipeline = [
    {"$project":
        {"date": {
            "year": {"$year": "$time"},
            "month": {"$month": "$time"},
            "day": {"$dayOfMonth": "$time"},
            "hour": {"$hour": "$time"},
            "minute": {"$subtract": [
                {"$minute": "$time"},
                {"$mod": [{"$minute": "$time"}, 10]}
            ]}
        }}
    },
    {"$group": {"_id": "$date", "count": {"$sum": 1}}}
]

从这个回答: https://stackoverflow.com/a/31550807/600559

1 个答案:

答案 0 :(得分:1)

我在LINQPad中编写了一些快速而脏的示例代码

void Main()
{
    var client = new MongoClient();
    var db = client.GetDatabase("db");
    var col = db.GetCollection<Foo>("foos");
    col.AsQueryable().Select(x => new Projection { Date = new Date { Year = x.Time.Year, Month = x.Time.Month, Day = x.Time.Day, Hour = x.Time.Hour } }).GroupBy(x => x.Date).Select(x => new Result { Count = x.Count(), Id = x.Key });
}

public class Foo
{
    public ObjectId Id {get;set;}
    public DateTime Time {get;set;}
    public string Bar {get;set;}
}

public class Projection
{
    public Date Date {get;set;}
}

public class Date
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
    public int Hour {get;set;}
}

public class Result
{
    public Date Id {get;set;}
    public int Count {get;set;}
}

基本上我所做的就是遵循C#驱动程序here上的文档。

我写了一些强类型的课程只是为了说明一些观点。从文档中的示例中可以看出,不需要它们。匿名类型就好了。 AsQueryable()方法只是通过转换程序将LINQ表达式运行到服务器上的聚合管道。我没有为你完全解决问题,但我希望你能得到主旨。

请记住,LINQ中有些内容无法在聚合框架中表达,所以即使编译它并不保证它会运行,所以请务必提前测试。