Mongodb聚合框架组和排序

编程入门 行业动态 更新时间:2024-10-26 13:22:10
本文介绍了Mongodb聚合框架组和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我具有以下文档结构...

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聚合框架组和排序

本文发布于:2023-11-22 19:08:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618645.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框架   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!