sau
sau

Reputation: 1356

call a mongo collection using a variable

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

Upvotes: 1

Views: 476

Answers (1)

Sede
Sede

Reputation: 61293

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]

Upvotes: 2

Related Questions