I have a client instance of my database and I would like to pass a database instance and the collection I want to use as a String to the client. Do you know how I can use String as attribute name?
db_url = "mongodb+srv://USER:[email protected]/a_company?retryWrites=true" \
"&w=majority"
Here is the function I would like to create:
def save_in_mongo(self, url, db, collection, perfume):
client = pymongo.MongoClient(url)
db = client.db
fragrance = db.collection
But I don't know how to use function arguments as MongoDB client attributes .
As stated in my comment , and from what I understand from your question, you can use the necessary values by passing them as strings as arguments.
In your method you see that you want to receive the
url
, the database, the collection and I imagine the document to be inserted ( perfume ).SOLUTION
From this, suppose that the function receives the following values:
url
: Connection string to Mongo Atlas:"mongodb+srv://USER:[email protected]?retryWrites=true&w=majority"
db
: String with the name of the database:"a_company"
col
: String with the name of the collection:"fragance"
doc
: Document to be inserted in the database.Note that the connection string does not include the database name.
Having this, we could make the function so that, given these parameters, it inserts the document in the collection:
Defining the function in this way, we can pass the parameters in the following way, for example:
I hope this helps you solve the problem.