I need read 2 collections data from MongoDB in Python, is there any way to join data in python?
Asked
Active
Viewed 5,082 times
2
-
1Welcome to Stack Overflow! Please try something out first and show us an minimal code example... https://stackoverflow.com/help/how-to-ask – phrogg Sep 25 '18 at 05:50
-
Similar to this perhaps : https://stackoverflow.com/q/2350495/9144250 – elpidaguy Sep 28 '18 at 08:36
2 Answers
6
Let's say that we have two collections(tables):
- buy_orders
- sell_orders
Those tables have the same field 'id_transaction' , and we want to join those tables on this field:
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' }
}])
To print results:
for item in result:
print(item)
For more references: MongoDB Docs and PyMongo Docs

Gajraj Singh Chouhan
- 390
- 1
- 7
- 14

mrberner
- 96
- 2
- 8
1
Have a look here
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"
}
}
])

Community
- 1
- 1

Boston Kenne
- 778
- 10
- 15