How to join MongoDB collections in Python?

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

+7
source share
3 answers

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

If possible, it is advisable to store all the data in one collection. If this is not possible, individual queries must be performed in all databases, and the data will be combined programmatically.

According to the documentation, you can link documents in separate collections either directly or with db links. Separate queries must still be run in each collection.

Similar questions were asked before. (I have included some links below.) We hope that the answers will give you some idea of ​​how the data is stored in MongoDB, and how you can restructure your documents and / or queries so that you can get the data you need with the least amount of queries to database.

Good luck

MongoDB and "join"

How to execute SQL Join equivalent in MongoDB?

How to join a request in mongodb?

"Initial Question on Joins" http://groups.google.com/group/mongodb-user/browse_thread/thread/edfcf8bd270274f9/

+12
source

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})

0
source

It seems that MongoDB version 4 now supports JOIN operation with the $lookup operator, which needs to be called inside the aggregation pipeline . However, this does not seem to be implemented in the pymongo driver, as for the latter purposes it did not produce anything from the python script.

0
source

Source: https://habr.com/ru/post/911101/


All Articles