我是mongo聚合的新手,
我的要求是展示user
及其last_activity_time
和last_activity
。
Collection Object:
{
"_id" : ObjectId("123456"),
"activity_count" : NumberLong(0),
"dt" : ISODate("2014-02-18T20:45:00.001Z"),
"job_functions" : [ ],
"joined_time" : ISODate("2014-01-27T22:53:57.024Z"),
"views_cnt" : NumberLong(6),
"last_activity" : "Login",
"last_activity_time" : ISODate("2014-02-18T20:56:43.552Z"),
"locations" : [ ],
"user_id" : "123456",
"user_name" : "User 1"
}
{
"_id" : ObjectId("789034"),
"activity_count" : NumberLong(0),
"dt" : ISODate("2014-02-18T21:45:00.001Z"),
"job_functions" : [ ],
"joined_time" : ISODate("2014-01-27T22:53:57.024Z"),
"views_cnt" : NumberLong(6),
"last_activity" : "Page View",
"last_activity_time" : ISODate("2014-02-18T20:56:43.552Z"),
"locations" : [ ],
"user_id" : "123456",
"user_name" : "User 1"
}
我需要
{
_id: {
user_id: "123456"
},
key: "123456",
user_name: "Ba Pub",
last_activity_time: "2014-02-18T20:56:43.552Z",
joined_time: "2014-01-27T22:53:57.024Z",
last_activity: "Page View"
}
我面临的问题是last_activity_time
,我可以获得max(last_activity_time)
,但是last_activity有点棘手。
感谢任何帮助。
答案 0 :(得分:0)
您可以在汇总管道中使用$ sort阶段(在分组阶段之前)按last_activity_time
降序排序,然后使用$first
运算符获取last_activity
答案 1 :(得分:0)
db.r_user.aggregate({
“$ match”:{“dt”:{“$ gte”:ISODate(“2013-12-12T18:30:00.000Z”),“$ lte”:ISODate(“2014-03-19T18:29:59.999Z” “)}}},
{ “$匹配”:{ “activity_count”:{ “$ GT”:0}}},
{ “$项目”:{ “U”:1, “USER_ID”:1, “USER_NAME”:1, “last_activity_time”:1, “job_functions”:1, “位置”:1,
“joined_time”:1,“first_visit_time”:1,“activity_count”:1,“last_activity”:1,“dt”:1}},
{ “$排序”:{ “last_activity_time”: - 1}},
{“$ group”:{“_ id”:{“user_id”:“$ user_id”},“key”:{“$ first”:“$ user_id”},“user_name”:{“$ first”:“$用户名”},
“last_activity_time”:{ “$最大”: “$ last_activity_time”}, “job_functions”:{ “$最后的”: “$ job_functions”},
“位置”:{ “$最后的”: “$位置”}, “joined_time”:{ “$最后的”: “$ joined_time”},
“first_visit_time”:{ “$分钟”: “$ first_visit_time”}, “activity_count”:{ “$总和”: “$ activity_count”},
“last_activity”:{“$ first”:“$ last_activity”}}},
{“$ sort”:{“activity_count”: - 1,“_ id”:1}},{“$ skip”:5},{“$ limit”:5}