【问题标题】:return document with latest subdocument only in mongodb aggregate仅在 mongodb 聚合中返回具有最新子文档的文档
【发布时间】:2013-05-06 00:13:09
【问题描述】:

我有这些 Mongoose Schemas:

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

如何返回所有线程及其最新的消息子文档(限制 1)?

目前,我正在服务器端过滤 Thread.find() 结果,但出于性能问题,我想使用 aggregate() 在 MongoDb 中移动此操作。

【问题讨论】:

    标签: node.js mongodb mongoose nosql


    【解决方案1】:

    您可以使用$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}}
    ]);
    

    【讨论】:

    • 如何返回没有消息的线程?我找不到很多关于条件的例子(除了你在 stackoverflow 上的答案)
    • @younes0 最好将其作为一个新问题提出。
    • 做得很好 - 像这样的简单结果有据可查且详细。
    猜你喜欢
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2020-04-26
    • 2017-07-17
    • 2015-01-04
    • 1970-01-01
    • 2015-10-31
    相关资源
    最近更新 更多