Damir
Damir

Reputation: 56189

How to join MongoDB collections in Python?

How to join ( in a sense of INNER JOIN from SQL ) two MongoDB collections in Python ? Do I need to use native map/reduce javascript code or to do this in PyMongo ? How to solve this with less code ?

Upvotes: 8

Views: 13708

Answers (3)

c24b
c24b

Reputation: 5552

MongoDB version 4 now seems to supports JOIN operation with the operator $lookup that you have to call inside an aggregation pipeline. However this seems not to be implemented in pymongo driver as for last intents it produced nothing from python script.

Upvotes: 0

jeremybcenteno
jeremybcenteno

Reputation: 139

You can use MongoJoin.

pip install mongojoin

Create a MongoCollection object:

collection = MongoCollection("db_name", "collection_name", ["collection_select_key_1", "collection_select_key_2"], {filter_key : filter_value})

Upvotes: 1

Marc
Marc

Reputation: 5548

Mongo stores data differently than in a traditional relational database, and does not support table joins as one might be used to in a SQL database. There is a note on this in the "Database References" documentation. http://www.mongodb.org/display/DOCS/Database+References

If possible, it is preferable to store all data in a single collection. If this is not possible, separate queries will have to be performed on all of the databases, and the data merged programmatically.

As per the documentation, it is possible to link documents in separate collections, either directly or with db references. Separate queries will still have to be performed on each collection.

Similar questions have been asked before. (I have included some links below.) Hopefully the responses will give you some additional insight into how data is stored in MongoDB, and how you can restructure your documents and/or queries such that you can retrieve the data that you need with the fewest number of requests to the database.

Good luck!

MongoDB and "joins"

How do I perform the SQL Join equivalent in MongoDB?

How to join query in mongodb?

"Beginner question regarding joins" http://groups.google.com/group/mongodb-user/browse_thread/thread/edfcf8bd270274f9/

Upvotes: 12

Related Questions