mongodb 多表查询

时间:2023-03-06 14:47:56

今天有一个业务涉及到mongodb的多表查询,大体记录下语句结构

db.table_a.aggregate([

{$lookup:{from:"table_b",localField:"userid",foreignField:"userid",as:"organization_doc"}},   //联表B
{
$project:{
_id:1,
cardid:1,
checkin_time:1,
checkin_date:1,
userid:1,
selfcare_ability:1,
checkout_time:1,
checkout_date:1,
inventory_doc:"$organization_doc.name"
}     //通过project参数限制返回数据,提高效率
},
{$lookup:{from:"table_c",localField:"cardid",foreignField:"cardid",as:"archives_doc"}},  //联表c

{$match:{"archives_doc.xingzheng_code" : "370213000001"}},   //匹配搜索条件condition
{$limit:10},{$skip:1}])   //其他参数,如条数显示,翻页,排序等