Hannah
Hannah

Reputation: 35

How can I dynamically create a name for a mongo database with Python?

I'm writing the backend of my app in Python and writing to a PyMongo database.

I'm setting up a few servers which I'd like to run simultaneously as nodes in a blockchain. In my prototype, I need each node to create there own collection in my database for their version of the blockchain, so for example blockchain-{insert node_id here} for each.

I'm pretty new to python and have been self teaching myself but struggling to combine .format method with creating these collections.

I know that this works:

client = MongoClient('mongodb://localhost:27017/')
db = client.my_blockchain
col_blockchain = db.name_of_blockchain

Result: Collection named "name_of_blockchain"

But when I try the following, I get an error:

col_blockchain = db['col_my_blockchain_{}'].format(node_id)

Result: Error:

TypeError: 'Collection' object is not callable. If you meant to call the 'format' method on a 'Collection' object it is failing because no such method exists.

Or when I try to save the name in a variable, I don't get a dynamic answer:

    col_blockchain_name = 'col_my_blockchain_{}'.format(node_id)
    col_blockchain = db.col_blockchain_name 

Result: Collection named "col_blockchain_name" for each server running (so not dynamic)

Upvotes: 2

Views: 1663

Answers (2)

Jeevan Chaitanya
Jeevan Chaitanya

Reputation: 1384

Use eval keyword, for calling mongo collection

eval('col_my_blockchain.{}'.format(node_id))

this works

Upvotes: -1

T Burgis
T Burgis

Reputation: 1435

This code:

col_blockchain = db['col_my_blockchain_{}'].format(node_id)

is looking for a dictionary element called col_my_blockchain_{} and when it has retrieved that it's trying to call the string format function on it. What you want to do is:

col_blockchain = db['col_my_blockchain_{}'.format(node_id)]

Which forms the dictionary key fully before trying to access it. All you need to do is move the ]

Upvotes: 5

Related Questions