【发布时间】: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的分组文档:docs.mongodb.org/manual/reference/method/db.collection.group
-
如果您想执行这些类型的查询,您应该将您的文档的
startTime更改为Date而不是数字。
标签: mongodb aggregation-framework