我需要在Python中从MongoDB中读取2个集合数据,有什么方法可以在python中联接数据?
答案 0 :(得分:1)
假设我们有两个集合(表):
这些表具有相同的字段'id_transaction',我们希望将这些表联接到该字段上:
import pymongo
my_client = pymongo.MongoClient('mongodb://localhost:27017/')
my_db = my_client['Orders']
my_collection = my_db['buy_orders']
result = my_collection..aggregate([ {'$lookup' : {'from': sell_orders','localField': 'id_transaction','foreignField': 'id_transaction','as': 'results' }}])
要打印结果:
for item in result:
print(item)
有关更多参考:MongoDB Docs和PyMongo Docs
答案 1 :(得分:0)
from bson.objectid import ObjectId
#the custom_id for reference
custom_id = ObjectId()
#creating user with the role admin
db.users.insert_one({"name": "Boston", "role_id": custom_id})
#Creating role with the custom id
db.roles.insert_one({"_id": custom_id, "name": "Admin")}
#lookup usage
db.users.aggregate([
{
"$lookup":
{
"from": "roles",
"localField": "role_id",
"foreignField": "_id",
"as": "roles"
}
}
])