mongodb的聚合,连表查询lookup

首先mongodb的聚合:

db.getCollection('表一').aggregate([
    { 
        $project: { 'year_data': {$year: "$createdAt"},
                            'month_data': {$month: "$createdAt"}
                            }
                           },
        {$group: {_id : {"year_data":"$year_data", "month_data":"$month_data"}, total : {$sum : 1}}}
           
])

lookup:连表查询


db.getCollection('表一').aggregate([
         {$lookup: {
                    from: "表二",
                    localField: "openId",
                    foreignField: "socials.openId", 
                    as: "member" 
                    }
         },
    { 
        $project: { 'year_data': {$year: "$createdAt"},
                            'month_data': {$month: "$createdAt"},
                            'member' :1
                }
        },
        {$group: {_id : {"year_data":"$year_data", "month_data":"$month_data"},
                          total : {$sum : 1}
                 }
        },
        {$sort: {"_id.year_data":-1, "_id.month_data":-1}}
])

其中这些字段是干什么的呢 :

  1. from: “要连接的表”,
  2. localField: “当前Collection中需要连接的字段”,
  3. foreignField: “外连Collection中连接查询的字段”,
  4. as: “把获取到的的值赋值给这个字段
    原文作者:firststep
    原文地址: https://www.jianshu.com/p/2cc1ae28a741
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞