return document with latest subdocument only in mongodb aggregate

前端 未结 1 1021
无人及你
无人及你 2020-12-20 02:14

I\'ve got these Mongoose Schemas:

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


        
相关标签:
1条回答
  • 2020-12-20 02:44

    You can use $unwind, $sort, and $group to do this using something like:

    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}}
    ]);
    
    0 讨论(0)
提交回复
热议问题