mongodb有$lookup可以做多表查询
举个例子
db.orders.aggregate([ { $lookup: { from: "inventory", localField: "item", foreignField: "sku", as: "inventory_docs" } } ])
上面的代码意思是,从order表中取item字段作为inventory表中sku的查询条件,然后把数据保存到inventory_docs字段
等价于db.inventory.find({‘sku‘:"item"})
下面用pymongo实现
from pymongo import MongoClient def test(): client = MongoClient() db = client[db_name] db[‘orders‘].aggregate([{‘$lookup‘:{‘from‘: "inventory", "localField": "item", "foreignField": "sku", "as": "inventory_docs"}}])
这样就实现了上述的效果了