仅在 mongodb 聚合中返回带有最新子文档的文档 [英] return document with latest subdocument only in mongodb aggregate
本文介绍了仅在 mongodb 聚合中返回带有最新子文档的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这些猫鼬模式:
var Thread = new Schema({
title: String, messages: [Message]
});
var Message = new Schema({
date_added: Date, author: String, text: String
});
如何返回所有带有最新消息子文档的线程(限制为 1)?
How do you return all Threads with their latest Message subdocument (limit 1) ?
目前,我正在服务器端过滤 Thread.find()
结果,但我想使用 aggregate()
在 MongoDb 中移动这个操作性能很重要.
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.
推荐答案
您可以使用 $unwind
、$sort
和 $group
使用以下方法执行此操作:
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}}
]);
这篇关于仅在 mongodb 聚合中返回带有最新子文档的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文