在聚合框架中给出完整时间戳时如何按日期聚合? [英] How to aggregate by date when a full timestamp is given in aggregation framework?

查看:17
本文介绍了在聚合框架中给出完整时间戳时如何按日期聚合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个错误集合,因此每个错误都带有一个 date 字段.如何仅按 DAY 聚合/计数/分组错误(即排除一天中的时间)?我想,应该应用一些智能投影.

I have a collection of errors, so that every error carries a date field. How can I aggregate/count/group the errors by DAY only (i.e. exclude the time of the day)? I guess, some smart projection should be applied.

推荐答案

您可以使用以下聚合运算符来做到这一点:

You can do this by using the following aggregation operators:

这将为您提供每个日期的错误计数:

This gives you the error count for each date:

db.errors.aggregate(
    { $group : {
        _id: {
            year : { $year : "$date" },        
            month : { $month : "$date" },        
            day : { $dayOfMonth : "$date" },
        },
        count: { $sum: 1 }
    }}
);

此示例假定错误文档中的日期字段为 date 并且类型为 BSON 日期.MongoDB 中还有一个 Timestamp 类型,但是文档明确不鼓励使用这种类型:

This example assumes that the date field in your error documents is date and of type BSON Date. There is also a Timestamp type in MongoDB, but use of this type is explicitely discouraged by the documentation:

注意:BSON Timestamp 类型供 MongoDB 内部使用.对于大多数情况下,在应用程序开发中,您将希望使用 BSON 日期类型.有关详细信息,请参阅日期.

Note: The BSON Timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.

这篇关于在聚合框架中给出完整时间戳时如何按日期聚合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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