Python高級教程(八)、Python之MongoDB

MongoDB 是目前最流行的 NoSQL 數(shù)據(jù)庫之一,使用的數(shù)據(jù)類型 BSON(類似 JSON)。

PyMongo

Python 要連接 MongoDB 需要 MongoDB 驅動,這里我們使用 PyMongo 驅動來連接。

pip 安裝

pip 是一個通用的 Python 包管理工具,提供了對 Python 包的查找、下載、安裝、卸載的功能。

安裝 pymongo:

python -m pip3 install pymongo

也可以指定安裝的版本:

python3 -m pip3 install pymongo==3.5.1

更新 pymongo 命令:

python3 -m pip3 install --upgrade pymongo

easy_install 安裝
舊版的 Python 可以使用 easy_install 來安裝,easy_install 也是 Python 包管理工具。

python -m easy_install pymongo

更新 pymongo 命令

 python -m easy_install -U pymongo

測試 PyMongo

接下來我們可以創(chuàng)建一個測試文件 demo_test_mongodb.py,代碼如下:


#!/usr/bin/python
 
import pymongo

執(zhí)行以上代碼文件,如果沒有出現(xiàn)錯誤,表示安裝成功。

創(chuàng)建數(shù)據(jù)庫

創(chuàng)建一個數(shù)據(jù)庫

創(chuàng)建數(shù)據(jù)庫需要使用 MongoClient 對象,并且指定連接的 URL 地址和要創(chuàng)建的數(shù)據(jù)庫名。

如下實例中,我們創(chuàng)建的數(shù)據(jù)庫 pythondb :

#!/usr/bin/python
 
import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pythondb"]

判斷數(shù)據(jù)庫是否已存在

我們可以讀取 MongoDB 中的所有數(shù)據(jù)庫,并判斷指定的數(shù)據(jù)庫是否存在:


#!/usr/bin/python
 
import pymongo
 
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
 
dblist = myclient.list_database_names()
# dblist = myclient.database_names() 
if "pythondb" in dblist:
  print("數(shù)據(jù)庫已存在!")

創(chuàng)建集合

MongoDB 中的集合類似 SQL 的表。

創(chuàng)建一個集合

MongoDB 使用數(shù)據(jù)庫對象來創(chuàng)建集合,實例如下:


#!/usr/bin/python
 
import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pythondb"]
 
mycol = mydb["sites"]

判斷集合是否已存在

我們可以讀取 MongoDB 數(shù)據(jù)庫中的所有集合,并判斷指定的集合是否存在:


#!/usr/bin/python
 
import pymongo
 
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
 
mydb = myclient['pythondb']
 
collist = mydb. list_collection_names()
# collist = mydb.collection_names()
if "sites" in collist:   # 判斷 sites 集合是否存在
  print("集合已存在!")

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容