【发布时间】:2019-02-28 16:11:48
【问题描述】:
我需要在 Python 中从 MongoDB 中读取 2 个集合数据,有什么方法可以在 python 中加入数据?
【问题讨论】:
-
欢迎来到 Stack Overflow!请先尝试一下,然后向我们展示一个最小的代码示例...stackoverflow.com/help/how-to-ask
标签: json pymongo mongo-collection
我需要在 Python 中从 MongoDB 中读取 2 个集合数据,有什么方法可以在 python 中加入数据?
【问题讨论】:
标签: json pymongo mongo-collection
假设我们有两个集合(表):
这些表具有相同的字段 '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
【讨论】:
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"
}
}
])
【讨论】: