mongodb - 在聚合框架中给出完整时间戳时如何按日期聚合?

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

最佳答案

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

  • $group
  • $year
  • $month
  • $dayOfMonth

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

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

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

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.

https://stackoverflow.com/questions/15657501/

相关文章:

ruby-on-rails - 查询 Mongoid 哈希字段

excel - NODE.JS: fatal error - JS 分配失败 - 进程内存不足,同时

mongodb - 文档数据库 : Redundant data, 引用等(特别是 MongoDB)

node.js - mongoDB 是否有重新连接问题或者我做错了?

node.js - 在 MongoDB 中删除时自动删除引用对象

java - Mongodb避免重复条目

c# - C#最成熟的MongoDB驱动是什么?

mongodb - 如何从 MongoDb 对象中删除属性?

node.js - Mongoose 对聚合结果进行排序

javascript - 如何在 meteor 应用程序中向 mongodb 添加两列唯一 ID?