简体   繁体   中英

How to use variable to select database in Pymongo

Usually I connect to a database in Pymongo like this:

    # connect to the MongoDB
    connection = MongoClient("mongodb://127.0.0.1:27017")

    # connect to the database
    self.db = self.connection.my_database

The problem is, the name of my_database always changes. How can I use a variable to choose the database?

Based on this documentation we can do it like this:

# connect to the MongoDB
connection = MongoClient("mongodb://127.0.0.1:27017")

# connect to the database
a = 'my_database'
self.db = self.connection[a]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM