python实现对mongodb数据库进行多表联合查询 lookup_yuer_xiao的博客-CSDN博客_pymongo 关联查询
$lookup (aggregation) — MongoDB Manual
result = db.ai_simples.aggregate( [ { '$lookup': { "from": "patient", # 需要联合查询的另一张表B "localField": "simples.ref_patient_id", # 表A的字段 "foreignField": "_id", # 表B的字段 "as": "patient_id" # 根据A、B联合生成的新字段名 }, }, { '$project': # 联合查询后需要显示哪些字段,1:显示 { 'patient_id.pid': 1, 'patient_id.name': 1, 'uuid': 1, 'simples.uuid':1, 'simples.ref_patient_id': 1, 'patient_id._id': 1, }, }, { '$match': # 根据哪些条件进行查询 { "uuid": '0038a346-ea85-4fe1-b365-e32e600141f4' # 这里是根据表A中 user_id == name } } ] ) for dic in result: # print(dic) for idx,simple in enumerate(dic['simples']): for patient in dic['patient_id']: if simple['ref_patient_id'] == patient['_id']: # print(idx,'/',len(dic['simples']), simple['uuid'],patient['_id'],patient['pid'],patient['name']) print(idx,'/',len(dic['simples']), simple['uuid'],patient['pid'],patient['name'])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)