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

时间:2013-05-11 12:20:31

标签: node.js mongodb mongoose nosql

我有这些Mongoose Schemas:

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中移动此操作。

1 个答案:

答案 0 :(得分: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}}
]);