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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM