Python Data Access 简明教程
Python MongoDB - Create Database
与其他数据库不同的是,MongoDB 没有提供单独用于创建数据库的命令。
Unlike other databases, MongoDB does not provide separate command to create a database.
一般来说,use 命令用于选择/切换到指定的数据库。此命令最初会验证我们指定的数据库是否存在,如果存在,则会连接到该数据库。如果我们使用 use 命令指定的数据库不存在,则会创建一个新数据库。
In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created.
因此,你可以在 MongoDB 中使用 @[s0] 命令创建一个数据库。
Therefore, you can create a database in MongoDB using the Use command.
Example
以下命令创建一个名为 mydb 的数据库。
Following command creates a database named in mydb.
>use mydb
switched to db mydb
你可以使用 db 命令验证你的创建操作,该命令会显示当前的数据库。
You can verify your creation by using the db command, this displays the current database.
>db
mydb
Creating database using python
要在使用 pymongo 连接到 MongoDB,你需要导入并创建一个 MongoClient,然后你可以直接访问你需要在属性 passion 中创建的数据库。
To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion.
Example
以下示例在 MangoDB 中创建一个数据库。
Following example creates a database in MangoDB.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
print("Database created........")
#Verification
print("List of databases after creating new one")
print(client.list_database_names())
Output
Database created........
List of databases after creating new one:
['admin', 'config', 'local', 'mydb']
你还可以创建 MongoClient 时指定端口和主机名,并可以使用字典风格访问数据库。
You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style.