问题描述
我具有以下文档结构...
I have the following document structure...
{
"id":"documentID"
"sessionId":"sometext"
"msg":"sometext"
"time":"date"
}
- sessionId可以存在于许多文档中
我想按sessionId
汇总文档,每个会话的结果应包含与该会话相关的消息集(按时间排序).
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.
使用MongoDB聚合框架如何实现?
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.
推荐答案
您可以执行以下操作:
db.collection.aggregate(
{$sort:{"time":1}},
{ $group:
{ _id: "$sessionId",
messages: { "$push": {message: "$msg", time: "$time"} }
}
}
)
这将根据时间对集合进行排序,然后按会话ID进行分组.每个会话ID组将具有一系列子文档,其中包含消息和消息的时间.通过排序然后推送消息,消息将按时间在您的消息数组中排序.
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.
这篇关于Mongodb聚合框架组和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!