mongodb aggregate 分页总数和数据同时获取

//演示插入的表结构

db.getCollection('tmp_article_user').insertMany([{
   name: 'admin',
   age:18
},
{
   name: 'xiaomin',
   age:19
}]);

 

db.getCollection('tmp_article').insertMany([{
   title: 'MongoDB Overview',
   description: 'MongoDB is no sql database',
   by_user: 'admin',
   likes: 100
},
{
   title: 'NoSQL Overview',
   description: 'No sql database is very fast',
   by_user: 'xiaomin',
   likes: 10
}])

 

///单表查询

db.getCollection('tmp_article').aggregate([
{$match:{}},
{$facet:{
       total: [{ $count:"count" }],
       rows:[{ $skip:0 },{ $limit: 3}]
     }
},
{
 $project: {
         data:"$rows",
         total: {$arrayElemAt: [ "$total.count", 0 ]},
    }
 }
]);

 //多表关联查询

db.getCollection('tmp_article').aggregate([
{$match:{}},
{$lookup:{
       from: "tmp_article_user",
       localField: "by_user",    // field in the orders collection
       foreignField: "name",  // field in the items collection
       as: "user_info"
     }
},
{$facet:{
       total: [{ $count:"count" }],
       rows:[{ $skip:0 },{ $limit: 3}]
     }
},
{
 $project: {
         data:"$rows",
         total: {$arrayElemAt: [ "$total.count", 0 ]},
    }
 }
]);

 

//多表多条件关联查询

db.getCollection('tmp_article').aggregate([
{$match:{}},
{$lookup:{
       from: "tmp_article_user",
       let: { user_name: "$by_user" },
       pipeline: [
          { $match:
             { $expr:
                { $and:
                   [{ $eq: [ "$name","$$user_name" ] }]
                }
             }
          },
        ],
        as: "user_info"
     }
},
{$facet:{
       total: [{ $count:"count" }],
       rows:[{ $skip:0 },{ $limit: 3}]
     }
},
{
 $project: {
         data:"$rows",
         total: {$arrayElemAt: [ "$total.count", 0 ]},
    }
 }
]);

 

posted @ 2022-03-07 18:59  super-caide  阅读(1657)  评论(0编辑  收藏  举报