仅在 mongodb 聚合中返回具有最新子文档的文档 [英] return document with latest subdocument only in mongodb aggregate

查看:18
本文介绍了仅在 mongodb 聚合中返回具有最新子文档的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些 Mongoose Schemas:

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

如何返回所有线程及其最新的消息子文档(限制 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆