
- Python MongoDB 教程
- Python MongoDB - 主頁
- Python MongoDB - 簡介
- Python MongoDB - 建立資料庫
- Python MongoDB - 建立集合
- Python MongoDB - 插入文件
- Python MongoDB - 查詢
- Python MongoDB - 查詢
- Python MongoDB - 排序
- Python MongoDB - 刪除文件
- Python MongoDB - 刪除集合
- Python MongoDB - 更新
- Python MongoDB - 限制
- Python MongoDB 有用資源
- Python MongoDB - 快速指南
- Python MongoDB - 有用資源
- Python MongoDB - 討論
Python MongoDB - 建立資料庫
與其他資料庫不同,MongoDB 並未提供建立資料庫的單獨命令。
通常,使用 use 命令來選擇/切換到特定資料庫。此命令最初會驗證我們指定的資料庫是否存在,若存在,則連線到該資料庫。如果我們使用 use 命令指定的資料庫不存在,則會建立一個新資料庫。
因此,你可以使用 use 命令在 MongoDB 中建立資料庫。
語法
use DATABASE 語句的基本語法如下所示 -
use DATABASE_NAME
示例
以下命令在 mydb 中建立了一個名為的資料庫。
>use mydb switched to db mydb
你可以使用 db 命令驗證你的建立,此命令會顯示當前資料庫。
>db mydb
使用 Python 建立資料庫
要使用 pymongo 連線到 MongoDB,你需要匯入並建立一個 MongoClient,然後你可以直接訪問你需要在屬性 passion 中建立的資料庫。
示例
以下示例在 MongoDB 中建立了一個數據庫。
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())
輸出
Database created........ List of databases after creating new one: ['admin', 'config', 'local', 'mydb']
你還可以指定建立 MongoClient 時的埠和主機名,並可以使用字典樣式訪問資料庫。
示例
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] print("Database created........")
輸出
Database created........
廣告