call a mongo collection using a variable

江枫思渺然 提交于 2021-02-10 15:13:13

问题


I have generic collection name in my mongodb and I want to use a string variable to call these collection. For example:

from pymongo import MongoClient
client= MongoClient()
db = client.mydb
collec_id='123'

mycollection = db.collection123

How can I get mycollectionusing collec_id

Any help appreciated


回答1:


As you seems noticed you cannot use dot (.) here. You need to use bracket [] to compute your collections' name. Here you use the + operator to concatenate collection and collect_id.

mycollection = db['collection' + collec_id]


来源:https://stackoverflow.com/questions/32270315/call-a-mongo-collection-using-a-variable

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