我需要在 Python 中从 MongoDB 读取 2 个集合数据,有没有办法在 python 中加入数据?
问问题
3198 次
2 回答
3
假设我们有两个集合(表):
- 购买订单
- 销售订单
这些表具有相同的字段 '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
于 2019-01-11T19:24:51.597 回答
1
看看这里
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"
}
}
])
于 2019-02-25T12:57:50.123 回答