我有这些Mongoose Schemas:
var Thread = new Schema({
title: String, messages: [Message]
});
var Message = new Schema({
date_added: Date, author: String, text: String
});
如何使用最新的Message子文档(限制1)返回所有线程?
目前,我正在过滤服务器端的Thread.find()
结果,但我想在性能问题上使用aggregate()
在MongoDb中移动此操作。
答案 0 :(得分: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}}
]);