Reez0
Reez0

Reputation: 2689

Use a string variable name for mongodb collection name

I've created a string

new_collection_name = "new_name"

And then tried to use that variable to reference the collection without any success.

for item in db.new_collection_name.find():

Is it actually possible to do this using a variable, or should I change my approach?

Upvotes: 1

Views: 670

Answers (1)

Endyd
Endyd

Reputation: 1279

You can use the vars() function to use a string to select another object.

The vars method returns the dict attribute for a module, class, instance, or any other object if the same has a dict attribute

for item in vars()['db.' + new_collection_name].find():

Upvotes: 2

Related Questions