1

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?

3
  • db.getCollection(new_collection_name).find() Commented Jan 8, 2019 at 19:12
  • You should be able to index with variable name as: db[new_collection_name].find() Commented Jan 8, 2019 at 19:12
  • Thanks guys, both suggestions work great. Feel free to add it as an answer and I'll accept it. Commented Jan 8, 2019 at 19:25

1 Answer 1

2

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():
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.