How to join MongoDB collections in Python?

…衆ロ難τιáo~ 提交于 2019-12-07 01:16:52

问题


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 ?


回答1:


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/




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/9771330/how-to-join-mongodb-collections-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!