【问题标题】:MongoDB Aggregate Query Group by DatesMongoDB 按日期聚合查询组
【发布时间】:2017-06-26 16:35:52
【问题描述】:

我在 mongoDB 中有以下集合

{ _id, startTime, duration }

所以基本的想法是相机会寻找人,一旦它检测到一个人,它就会保存 startTime,一旦一个人消失,它就会保存持续时间。 所以实体基本上说“一个人出现在 X 时间并且在相机范围内持续了 Y 毫秒”。 startTime 和 duration 都是数值。

所以,我想执行各种查询,例如: 1.给我每月/每年的人数 2.给我每月持续时间> 5000ms的人数

等等

虽然我对 MongoDB 还很陌生,但我在聚合框架方面遇到了一些问题,所以如果有人告诉我如何执行上述查询以获得某种排序,我将不胜感激领先一步。

编辑:

好的,我已经尝试了几次,但没有运气。现在我的对象有这种形式:

{
  "_id" : ObjectId("52de407c75895eaf5ea99715"),
  "startTime" : "new Date('02 01 2011 08:36:54')",
  "duration" : 27000
}

我正在尝试这个查询:

 db.collection.aggregate(
        {$project : {
             year : {$year : "$startTime"}

        }},
        {$group : {
             _id : {year : "$year"}, 
             count : {$sum : 1}
        }}
    )

但我收到以下异常:

Error occurred in performing aggregation
Command 'aggregate' failed: exception: can't convert from BSON type String to Date (response: { "errmsg" : "exception: can't convert from BSON type String to Date", "code" : 16006, "ok" : 0.0 })
Type: MongoDB.Driver.MongoCommandException
Stack:    at MongoDB.Driver.Operations.CommandOperation`1.Execute(MongoConnection connection)
   at MongoDB.Driver.MongoCollection.RunCommandAs[TCommandResult](IMongoCommand command, IBsonSerializer resultSerializer, IBsonSerializationOptions resultSerializationOptions)
   at MongoDB.Driver.MongoCollection.RunCommandAs[TCommandResult](IMongoCommand command)
   at MongoDB.Driver.MongoCollection.Aggregate(IEnumerable`1 operations)
   at MangoUI.ComAggregate.kRemove_Click(Object sender, EventArgs e)
Inputs:: 
Command:  aggregate
Ok:       False
ErrorMsg: exception: can't convert from BSON type String to Date
Request:  { "aggregate" : "person", "pipeline" : [{ "$project" : { "year" : { "$year" : "$startTime" } } }, { "$group" : { "_id" : { "year" : "$year" }, "count" : { "$sum" : 1 } } }] }
Response: { "errmsg" : "exception: can't convert from BSON type String to Date", "code" : 16006, "ok" : 0.0 }

【问题讨论】:

标签: mongodb aggregation-framework


【解决方案1】:

您可以使用聚合框架来完成。

给我每月/每年的人数

db.collection.aggregate(
    {$project : {
         year : {$year : "$startTime"}, 
         month : {$month : "$startTime"}
    }},
    {$group : {
         _id : {year : "$year", month : "$month"}, 
         count : {$sum : 1}
    }}
)

给我每月持续时间> 5000ms的人数

db.collection.aggregate(
    {$project : {
         year : {$year : "$startTime"}, 
         month : {$month : "$startTime"}, 
         duration: {$cond: [{$gt: ['$duration', 5000]}, 1, 0]}
    }},
    {$group : {
         _id : {year : "$year",month : "$month"}, 
         duration : {$sum : "$duration"}
    }}
)

更多信息请查看Aggregation Framework.

【讨论】:

  • 我尝试了第一个,但我似乎得到了以下异常:命令“聚合”失败:异常:无法从 BSON 类型 NumberLong64 转换为日期(响应:{“errmsg”: “异常:无法从 BSON 类型 NumberLong64 转换为 Date”,“code”:16006,“ok”:0.0 })
  • 我忘了说。为了使用 $year 和 $month 运算符 startTime 应该是 Date 格式。它不适用于 Long。
  • 我可以即时进行转换吗?我尝试了几种方法,但似乎都不起作用。
  • 据我所知,没有办法即时将 long 转换为 date。
  • 你不知道这对我有多大帮助。 +1
【解决方案2】:

请参考MongoDB兼容数据格式http://docs.mongodb.org/manual/reference/bson-types/#document-bson-type-date

下面是测试聚合的方法。

 rs1:PRIMARY> 
rs1:PRIMARY> db.dbversitycol.insert({ "_id" : "1", "LastUpdatedOn" : new Date() , "company" : "microsoft" })
rs1:PRIMARY> db.dbversitycol.insert({ "_id" : "2", "LastUpdatedOn" : new Date() , "company" : "google" })
rs1:PRIMARY> db.dbversitycol.insert({ "_id" : "3", "LastUpdatedOn" : new Date() , "company" : "ibm" })
rs1:PRIMARY> db.dbversitycol.insert({ "_id" : "4", "LastUpdatedOn" : new Date() , "company" : "cisco" })
rs1:PRIMARY> db.dbversitycol.insert({ "_id" : "5", "LastUpdatedOn" : new Date() , "company" : "dbversity.com" })
rs1:PRIMARY> 
rs1:PRIMARY> db.dbversitycol.find()
{ "_id" : "1", "LastUpdatedOn" : ISODate("2014-11-28T13:09:13.203Z"), "company" : "microsoft" }
{ "_id" : "2", "LastUpdatedOn" : ISODate("2014-11-28T13:09:13.207Z"), "company" : "google" }
{ "_id" : "3", "LastUpdatedOn" : ISODate("2014-11-28T13:09:13.210Z"), "company" : "ibm" }
{ "_id" : "4", "LastUpdatedOn" : ISODate("2014-11-28T13:09:13.213Z"), "company" : "cisco" }
{ "_id" : "5", "LastUpdatedOn" : ISODate("2014-11-28T13:09:14.035Z"), "company" : "dbversity.com" }
rs1:PRIMARY> 
rs1:PRIMARY> 
rs1:PRIMARY> db.dbversitycol.aggregate(
... {
...     "$project" :
...     {
...        _id : 0,
...        "datePartDay" : {"$concat" : [
...            {"$substr" : [{"$dayOfMonth" : "$LastUpdatedOn"}, 0, 2]}, "-",
...            {"$substr" : [{"$month" : "$LastUpdatedOn"}, 0, 2]}, "-",
...            {"$substr" : [{"$year" : "$LastUpdatedOn"}, 0, 4]}
...       ] }
...     }
... },
... { "$group" :
...     { "_id" : "$datePartDay", "Count" : { "$sum" : 1 } }
...     }
... )
{ "result" : [ { "_id" : "28-11-2014", "Count" : 5 } ], "ok" : 1 }
rs1:PRIMARY> 
rs1:PRIMARY> 



rs1:PRIMARY> db.dbversitycol.aggregate(
...     {$project : {
...          year : {$year : "$LastUpdatedOn"}, 
...          month : {$month : "$LastUpdatedOn"}
...     }},
...     {$group : {
...          _id : {year : "$year", month : "$month"}, 
...          count : {$sum : 1}
...     }}
... )
{
        "result" : [
                {
                        "_id" : {
                                "year" : 2014,
                                "month" : 11
                        },
                        "count" : 5
                }
        ],
        "ok" : 1
}
rs1:PRIMARY>

您可以在http://www.dbversity.com/查看更多相关帖子

【讨论】: