return document with latest subdocument only in mo

2019-01-27 00:49发布

问题:

I've got these Mongoose Schemas:

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

How do you return all Threads with their latest Message subdocument (limit 1) ?

Currently, I'm filtering the Thread.find() results on the server side but I'd like to move this operation in MongoDb using aggregate() for performance matters.

回答1:

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}}
]);