0

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 ?

GuyOlivier
  • 183
  • 5
  • 13

2 Answers2

2

Finally I get it working, here is the full code:

from pymongo import MongoClient

# connect to MongoDB, change the << MONGODB URL >> to reflect your own connection string
client = MongoClient(<< MONGODB URL >>)
db=client.mydb

docs = db.collection1.aggregate([{"$lookup":{
            "from": "collection2",       # other table name
            "localField": "code",        # key field in collection 2
            "foreignField": "code",      # key field in collection 1
            "as": "linked_collections"   # alias for resulting table
        }},
        {"$project": {"code": 1, "field_from_collection1": 1, "field_from_collection2": 1}}
        ])

#$project is to select fields we need, we could ommit it

for doc in docs:        
    print(doc)
GuyOlivier
  • 183
  • 5
  • 13
0

So I feel like there are two parts to your question:

How do you do more complicated queriers with pymongo? How do you do a join with mongo?

The first question is pretty simple, you can declare any type of query and just use find({<your query>}). Here's an example from W3

The answer to your main question is more complicated. Here's another stack article where it's talked about in more detail. But basically since 3.2 you can use $lookup to do joins.