Mongodb聚合查找记录限制

时间:2017-09-12 10:19:58

标签: mongodb mongoose mongodb-query aggregation-framework

我的moongose + mongodb中有这个功能:

   Blog.aggregate([{
                "$match": {"user_id": userblog}},
                {
                "$lookup": {
                    from: "comments", // collection name in db
                    localField: "_id",
                    foreignField: "blogid",
                    as: "comments"
                },                  
            }]).exec(function(err, docs) {


            });

这完美无缺,但我怎样才能限制评论并追溯最近10条记录?非常感谢。马可。

2 个答案:

答案 0 :(得分:1)

为您的代码添加限制

Blog.aggregate([{
        "$match": {"user_id": userblog}},
        {
        "$lookup": {
            from: "comments", // collection name in db
            localField: "_id",
            foreignField: "blogid",
            as: "comments"
        }
    }]).limit(10).exec(function(err, docs) {

    });

答案 1 :(得分:0)

只需在聚合中添加限制:

Blog.aggregate([{
                "$match": {"user_id": userblog}},
                {
                "$lookup": {
                    from: "comments", // collection name in db
                    localField: "_id",
                    foreignField: "blogid",
                    as: "comments"
                }, 
                {
                    "$limit" : 10
                }                 
            }]).exec(function(err, docs) {


            });