当一个是日期字段时如何在MongoDB中按多个字段分组 [英] How to group by multiple fields in MongoDB when one is a date field

查看:214
本文介绍了当一个是日期字段时如何在MongoDB中按多个字段分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对MongoDB还是很陌生,我想弄清楚当其中一个是计算出的日期字段时,如何对多个字段进行分组:

I'm still very new to MongoDB and I'm trying to figure out how to group by more than one field when one of them is a calculated date field:

我的数据看起来像这样(简化):

My data looks like this (simplified):

{
    "_id" : ObjectId("52d6ed19e4b0a491abb53ff2"),
    "build_duration" : 667075,
    "build_number" : 40,
    "build_result" : "SUCCESS",
    "build_timestamp" : ISODate("2014-01-15T20:07:27.324Z"),
    "job_name" : "ABC"
}

我知道我可以做这样的事情来按多个字段分组:

I know that I can do something like this to group by more than one field:

db.builds.aggregate(
   { $group: { _id: { build_result: "$build_result", job_name: "$job_name"},
           build_duration: { $avg: "$build_duration" } } }
)

但是,如果我尝试使用$ dayOfYear函数对日期进行分组,则会出现错误:

However, if I try to group on the date using the $dayOfYear function I get an error:

db.builds.aggregate(
   { $group: { _id: { build_result: "$build_result", $dayOfYear: "$build_timestamp"},
           build_duration: { $avg: "$build_duration" } } }
)

错误:

Error: Printing Stack Trace
    at printStackTrace (src/mongo/shell/utils.js:37:15)
    at DBCollection.aggregate (src/mongo/shell/collection.js:897:9)
    at (shell):1:11
Thu Jan 16 13:34:08.036 aggregate failed: {
    "errmsg" : "exception: the operator must be the only field in a pipeline object (at '$dayOfYear'",
    "code" : 15983,
    "ok" : 0
} at src/mongo/shell/collection.js:898

所需的输出将是按日期和build_result进行分组,并加上build_duration的平均值.预先感谢.

The desired output would be a grouping by date and by build_result with an average of the build_duration. Thanks in advance.

推荐答案

您需要使用$dayOfYear对象作为_id中新字段的值,如下所示:

You need to use the $dayOfYear object as the value of a new field in your _id, like this:

db.builds.aggregate(
    { $group: { 
        _id: { 
            build_result: "$build_result", 
            dayOfYear: { $dayOfYear: "$build_timestamp" }
        },
        build_duration: { $avg: "$build_duration" } 
    } }
)

输出:

{
  "result": [
    {
      "_id": {
        "build_result": "SUCCESS",
        "dayOfYear": 15
      },
      "build_duration": 667075
    }
  ],
  "ok": 1
}

这篇关于当一个是日期字段时如何在MongoDB中按多个字段分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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