本文介绍了仅在mongodb聚合中返回带有最新子文档的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下猫鼬模式:
var Thread = new Schema({ title: String, messages: [Message] }); var Message = new Schema({ date_added: Date, author: String, text: String });如何返回所有线程及其最新的Message子文档(限制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聚合中返回带有最新子文档的文档
发布评论