MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Rückgabedokument mit letztem Filialdokument nur in Mongodb-Aggregat

Sie können $unwind verwenden , $sort und $group Verwenden Sie dazu etwas wie:

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