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