2

我有这些猫鼬模式:

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

您如何返回所有线程及其最新消息子文档(限制 1)?

目前,我正在过滤Thread.find()服务器端的结果,但我想在 MongoDb 中将此操作aggregate()用于性能问题。

4

1 回答 1

5

您可以使用$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}}
]);
于 2013-05-11T15:38:15.727 回答