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: "把获取到的的值赋值给这个字段

你可能感兴趣的:(mongodb的聚合,连表查询lookup)