注意:我在输出中只提供了一些文档以保持帖子小而直观
源集合:
{
"_id" : {
"SpId" : 840,
"Scheduler_Id" : 1,
"Channel_Id" : 2,
"TweetId" : 15
},
"PostDate" : ISODate("2013-10-31T18:30:00Z")
}
{
"_id" : {
"SpId" : 840,
"Scheduler_Id" : 1,
"Channel_Id" : 2,
"TweetId" : 16
},
"PostDate" : ISODate("2013-10-31T18:30:00Z")
}
{
"_id" : {
"SpId" : 840,
"Scheduler_Id" : 1,
"Channel_Id" : 2,
"TweetId" : 17
},
"PostDate" : ISODate("2013-10-30T18:30:00Z")
}
第 1 步:按 PostDate 分组
询问 :
db.Twitter_Processed.aggregate({$match : { "_id.SpId" : 840, "_id.Scheduler_Id" : 1 }},{$project:{SpId : "$_id.SpId",Scheduler_Id : "$_id.Scheduler_Id",day:{$dayOfMonth:'$PostDate'},month:{$month:'$PostDate'},year:{$year:'$PostDate'}, senti : "$Sentiment"}}, {$group : {_id : {SpId : "$SpId", Scheduler_Id : "$Scheduler_Id",day:'$day',month:'$month',year:'$year'}, sentiment : { $sum : "$senti"}}}, {$group : {_id : "$_id" , avgSentiment : {$avg : "$sentiment"}}})
输出 :
{
"result" : [
{
"_id" : {
"SpId" : 840,
"Scheduler_Id" : 1,
"day" : 31,
"month" : 10,
"year" : 2013
},
"avgSentiment" : 2.2700000000000005
},
{
"_id" : {
"SpId" : 840,
"Scheduler_Id" : 1,
"day" : 30,
"month" : 10,
"year" : 2013
},
"avgSentiment" : 4.96
}
}
第 2 步:尝试实现这一目标:
{
"result" : [
{
"_id" : {
"SpId" : 840,
"Scheduler_Id" : 1,
"Date" : ISODate("2013-10-31T18:30:00Z")
},
"avgSentiment" : 2.2700000000000005
},
{
"_id" : {
"SpId" : 840,
"Scheduler_Id" : 1,
"Date" : ISODate("2013-10-31T18:30:00Z")
},
"avgSentiment" : 4.96
}
}
我尝试的查询:
db.Twitter_Processed.aggregate({$match : { "_id.SpId" : 840, "_id.Scheduler_Id" : 1 }},{$project:{SpId : "$_id.SpId",Scheduler_Id : "$_id.Scheduler_Id",day:{$dayOfMonth:'$PostDate'},month:{$month:'$PostDate'},year:{$year:'$PostDate'}, senti : "$Sentiment"}}, {$group : {_id : {SpId : "$SpId", Scheduler_Id : "$Scheduler_Id",day:'$day',month:'$month',year:'$year'}, sentiment : { $sum : "$senti"}}}, {$group : {_id : "$_id" , avgSentiment : {$avg : "$sentiment"}}}, {$project : {_id : {SpId : "$_id.SpId",Scheduler_Id : "$_id.Scheduler_Id", date : new Date("$_id.year","$_id.month","$_id.day")}, avgSentiment : "$avgSentiment"}})
输出(错误):
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:22
Tue Dec 31 09:41:42.916 JavaScript execution failed: aggregate failed: {
"errmsg" : "exception: disallowed field type Date in object expression (
at 'date')",
"code" : 15992,
"ok" : 0
} at src/mongo/shell/collection.js:L898
如何实现第 2 步?