2

私はこれらのマングーススキーマを持っています:

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

最新のメッセージ サブドキュメント (制限 1) を含むすべてのスレッドを返すにはどうすればよいですか?

現在、サーバー側で結果をフィルタリングしていますが、パフォーマンスの問題Thread.find()を使用して、この操作を MongoDb に移動したいと考えています。aggregate()

4

1 に答える 1

5

$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}}
]);
于 2013-05-11T15:38:15.727 に答える