Home:ALL Converter>Query with join on mutiple collections with python in MongoDB

Query with join on mutiple collections with python in MongoDB

Ask Time:2020-03-19T01:21:15         Author:GuyOlivier

Json Formatter

I am newbie to MongoDB and Python (using pymongo 3.10.1). I can query one collection but I need to perform a join with two collections

collection1 {
    code
    some other fields
}

collection2 {
    code
    some other fields
}

I would like to achieve: select * from collection2 left inner join collection1 on collection2.code = collection1.code

I found only basic examples for queries with Python to MongoDB. How to achieve this with Python ? Could I use .aggregate and $lookup with Pythonn ?

Author:GuyOlivier,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60744517/query-with-join-on-mutiple-collections-with-python-in-mongodb
GuyOlivier :

Finally I get it working, here is the full code:\n\nfrom pymongo import MongoClient\n\n# connect to MongoDB, change the << MONGODB URL >> to reflect your own connection string\nclient = MongoClient(<< MONGODB URL >>)\ndb=client.mydb\n\ndocs = db.collection1.aggregate([{\"$lookup\":{\n \"from\": \"collection2\", # other table name\n \"localField\": \"code\", # key field in collection 2\n \"foreignField\": \"code\", # key field in collection 1\n \"as\": \"linked_collections\" # alias for resulting table\n }},\n {\"$project\": {\"code\": 1, \"field_from_collection1\": 1, \"field_from_collection2\": 1}}\n ])\n\n#$project is to select fields we need, we could ommit it\n\nfor doc in docs: \n print(doc)\n",
2020-03-19T07:28:50
yy