node.js - 如何使用时间戳作为mongodb和nodejs中的字段按天对记录进行分组

标签 node.js mongodb mongodb-query aggregation-framework

我想按天对特定时间段内的记录进行分组。到目前为止,我已经尝试使用添加到聚合函数中的代码:

 {
    $group : {
         _id : {  day: { $dayOfMonth: "$timestamp" }},
         count: { $sum: 1 }
      }
 }

这就是文档的样子:

{
"_id" : ObjectId("ec9cddd50e08a84cd3f4cccb"),
"orgid" : "5c48500d84430a3a4b828e85",
"timestamp" : ISODate("2019-03-28T14:00:00.000Z"),
"apiid" : {
    "zxczxczxczxczxc" : {
        "errortotal" : 6,
        "hits" : 6,
        "humanidentifier" : "Feedback",
        "identifier" : "663cfc345e42401c6443cfd635301f8f",
        "lasttime" : ISODate("2019-03-28T14:58:07.355Z"),
        "success" : 0,
        "totalrequesttime" : 0.0,
        "requesttime" : 0.0
    }
},
"apikeys" : {
    "00000000" : {
        "errortotal" : 3,
        "hits" : 3,
        "humanidentifier" : "",
        "identifier" : "00000000",
        "lasttime" : ISODate("2019-03-28T14:55:10.438Z"),
        "success" : 0,
        "totalrequesttime" : 0.0,
        "requesttime" : 0.0
    },
    "cae81afc" : {
        "errortotal" : 3,
        "hits" : 3,
        "humanidentifier" : "EE5RqcXMTqcWEx8nZv3vRATLspK2",
        "identifier" : "cbe81afc",
        "lasttime" : ISODate("2019-03-28T14:58:07.355Z"),
        "success" : 0,
        "totalrequesttime" : 0.0,
        "requesttime" : 0.0
    }
}

知道如何实现这一目标吗?

我得到的结果是:[ { _id: { day: null }, count: 3 } ],这对我来说似乎是错误的,因为我有两个具有相同日期的文档和另一个具有不同时间戳的文档

更新: 我也有这个内部聚合功能:

  // Project things as a key/value array, along with the original doc
                {
                    $project: {
                        array: {$objectToArray: '$apikeys'},
                        doc: '$$ROOT',
                    }
                },

                // Match the docs with a field value of 'x'
                {$match: {'array.v.humanidentifier': {$in: trialCustomerUsers}}},

如果我评论这部分,它会很好地进行分组,但问题是,如果我也不知道关键是什么,我也会做一些 where 语句,这就是为什么我必须添加这段代码

最佳答案

只需使用 $push 运算符将记录累积到新字段

{
    $group : {
         _id : {  day: { $dayOfMonth: "$timestamp" }},
         records: { $push: "$$ROOT" }
      }
 }

关于node.js - 如何使用时间戳作为mongodb和nodejs中的字段按天对记录进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55498511/

相关文章:

java - 如何用java编写接送服务函数

php - 比较 MongoDB 中的文档

node.js - 如何在 Feathers js 中使用传统 session

node.js - ExpressJS 路由 + Websockets - 共享端口

MongoDB - 查询过去几个小时内创建的所有文档,并按分钟分组?

mongodb检查点是否在多边形中

mongodb - 在 $sort 聚合管道之后向文档添加字段,该管道使用 MongoDb 聚合将其索引包含在排序列表中

java - 如何从 mongoDB 检索值?

javascript - mongodb mongoose find - 如何获取适用的字符串作为结果?

javascript - Q.js : How can I rewrite an async series flow in Q. js?