【问题标题】:MongoDB using a C# driver and time interval LINQMongoDB 使用 C# 驱动程序和时间间隔 LINQ
【发布时间】:2018-01-25 12:53:25
【问题描述】:

当使用 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

【问题讨论】:

    标签: c# mongodb linq aggregation-framework


    【解决方案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 中表达,但无法在聚合框架中表达,因此即使编译了某些东西也不能保证它会运行,因此请务必提前测试。

    【讨论】:

    • 但这不会将结果分组为相等的间隔?可以? GroupBy(x => x.Date) 看起来像是分组为日期?
    • 如果您查看Date 对象,您会看到它包含YearMonthDayHour,这意味着它将数据分组到一个小时长的桶中.如果您需要更细粒度的分桶,则需要修改代码以包含更多 DateTime 部分。话虽如此,此答案旨在为您提供解决特定问题的工具,而不是为您解决问题。毕竟,编码的一半乐趣在于解决问题。
    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多