我有这些猫鼬模式:
var Thread = new Schema({ title: String, messages: [Message] }); var Message = new Schema({ date_added: Date, author: String, text: String });
如何使用最新的Message子文档(限制1)返回所有线程?
目前,我正在Thread.find()
服务器端过滤结果,但我想在aggregate()
性能问题上使用MongoDb中的此操作.
您可以使用$unwind
,$sort
和$group
使用以下内容执行此操作:
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}} ]);