与最新的子文档仅在MongoDB中总回报文件(return document with latest

2019-09-02 15:05发布

我有这些猫鼬架构:

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

你如何返回与他们的最新消息子文档(限1)所有主题?

目前,我过滤Thread.find()在服务器端的结果,但我想使用MongoDB中移动该操作aggregate()的性能问题。

Answer 1:

您可以使用$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}}
]);


文章来源: return document with latest subdocument only in mongodb aggregate