【问题标题】:Mongoose Mongodb sorting and limiting query of subdocumentsMongoose Mongodb 子文档的排序和限制查询
【发布时间】:2015-12-20 16:17:49
【问题描述】:

我有以下设计架构:

 {
      participants: [String],
      conversations: [{
          date: Date
          messages: [String]
      }]
 }

现在我想获得 6 个最新的对话。我已经尝试了很多,但我似乎无法找到解决方案。我可以按子文档排序,但最后如果 1 个文档有 6 个最新的对话,则查询最终会给我这个文档加上 5 个其他文档。我想在查询结束时得到一个这样的数组,或者能够得到这个特定的信息:

[{date:'Adate', messages:[]},{date:'Adate2',messages:[]}]

感谢您的帮助!

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    实际上,如果您使用的 mongoDB 版本低于 3.1.6,则使用单个查询是不可能的。

    mongoDB version 3.1.6 and above 中的聚合管道支持$Slice

    如果您的 mongoDB 版本低于 3.1.6,那么您可以尝试以下代码:

    db.collection.aggregate([
    { $unwind : "conversations"},
    { $sort : {_id : 1, conversations.date : -1}},
    { $group: { _id : "$_id"} , conversations : { $push : "$conversations"}, participants : {$first : "$participants"} },
    { $project :  { _id : 1, conversations : 1, participants : 1 } }
    ]).forEach( function(doc)
                    { 
    
                        if( doc.conversations.length > 6)
                        {
                            var count = doc.conversations.length - 6;
                            doc.conversations.splice(6, count );
                        }
                    }
                )
    

    3.1.6以下版本的StackOverflow上有类似的问题,请查看the link

    对于mongoDb Version 3.1.6 and above,可以在聚合管道中使用$Slice来限制数组的内容。

    试试下面的代码:

    db.collection.aggregate([
    { $unwind : "conversations"},
    { $sort : {_id : 1, conversations.date : -1}},
    { $group: { _id : "$_id"} , conversations : { $push : "$conversations"}, participants : {$first : "$participants"} },
    { $project :  
                    { 
                        _id : 1, 
                        participants : 1, 
                        newconversations : 
                                            { 
                                                conversations : { $slice : 6 } 
                                            } 
                    } 
    }
    ])
    

    【讨论】:

    • 谢谢你,很抱歉迟到了,正在出差。
    猜你喜欢
    • 2021-07-19
    • 1970-01-01
    • 2020-08-02
    • 2018-04-05
    • 2013-04-06
    • 2017-10-01
    • 1970-01-01
    • 2013-04-18
    • 2015-04-27
    相关资源
    最近更新 更多