仅在 mongodb 聚合中返回带有最新子文档的文档

编程入门 行业动态 更新时间:2024-10-20 20:30:41
本文介绍了仅在 mongodb 聚合中返回带有最新子文档的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这些猫鼬模式:

var Thread = new Schema({ title: String, messages: [Message] }); var Message = new Schema({ date_added: Date, author: String, text: String });

如何返回所有带有最新消息子文档的线程(限制为 1)?

How do you return all Threads with their latest Message subdocument (limit 1) ?

目前,我正在服务器端过滤 Thread.find() 结果,但我想使用 aggregate() 在 MongoDb 中移动这个操作性能很重要.

Currently, I'm filtering the Thread.find() results on the server side but I'd like to move this operation in MongoDb using aggregate() for performance matters.

推荐答案

您可以使用 $unwind、$sort 和 $group使用以下方法执行此操作:

You can use $unwind, $sort, and $group to do this using something like:

Thread.aggregate([ // Duplicate the docs, one per messages element. {$unwind: '$messages'}, // Sort the pipeline to bring the most recent message to the front {$sort: {'messages.date_added': -1}}, // Group by _id+title, taking the first (most recent) message per group {$group: { _id: { _id: '$_id', title: '$title' }, message: {$first: '$messages'} }}, // Reshape the document back into the original style {$project: {_id: '$_id._id', title: '$_id.title', message: 1}} ]);

更多推荐

仅在 mongodb 聚合中返回带有最新子文档的文档

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

发布评论

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

>www.elefans.com

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