return document with latest subdocument only in mongodb aggregate

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.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

    // 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}}

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x