Mongodb Aggregation framework group and sort

这一生的挚爱 提交于 2019-12-21 06:55:34

问题


I have the following document structure...

{
  "id":"documentID"
  "sessionId":"sometext"
  "msg":"sometext"
  "time":"date"
}
  • sessionId can exist in many documents

I want to aggregate the documents by sessionId, the result for each session should contain the set of messages related to the session sorted by time.

Using the MongoDB aggregation framework how can I achieve that?

I have tried to sort first and then group but the messages in each session wasn't sorted for some reason:

{ $sort: { "time": 1 } },
{ "$group" : { 
    "_id" : "$sessionId", 
    "msgs" : { "$addToSet" : "$msg" }
} }

any suggestions? your answer is highly appreciated.


回答1:


You can do this:

db.collection.aggregate( 
    {$sort:{"time":1}},
    { $group:
        { _id: "$sessionId",
        messages: { "$push": {message: "$msg", time: "$time"} }
        }
    } 
)

This will sort the collection based on time then group by session id. Each session ID group will have an array of sub-documents which contain the message and time of the message. By sorting then pushing the messages will be ordered by time in your messages array.



来源:https://stackoverflow.com/questions/18242953/mongodb-aggregation-framework-group-and-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!