首先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}}
])
其中这些字段是干什么的呢 :
- from: “要连接的表”,
- localField: “当前Collection中需要连接的字段”,
- foreignField: “外连Collection中连接查询的字段”,
- as: “把获取到的的值赋值给这个字段