Python操作MongoDB的教程分享
一、前言
MongoDB 是一個流行的 NoSQL 數(shù)據(jù)庫,以其半結(jié)構(gòu)化的文檔存儲方式而聞名。Python開發(fā)人員經(jīng)常使用MongoDB來存儲和處理各種類型的數(shù)據(jù)。本文將帶你逐步了解如何使用Python與MongoDB進(jìn)行交互,從連接到基本操作。
二、安裝MongoDB驅(qū)動程序
安裝了MongoDB的Python驅(qū)動程序 pymongo
pip install pymongo
三、連接到MongoDB數(shù)據(jù)庫
首先,確保MongoDB服務(wù)器正在運(yùn)行。
接著,我們再連接到MongoDB數(shù)據(jù)庫。使用 pymongo 庫的 MongoClient 類來建立連接:
try:
client = MongoClient('mongodb://localhost:27017/')
print("數(shù)據(jù)庫連接成功")
except Exception as e:
print("數(shù)據(jù)庫連接失敗,原因:", e)可以根據(jù)你的服務(wù)器配置修改連接字符串,如下所示:
# 配置連接信息
host = 'localhost'
port = 27017
username = '<YourUsername>'
password = '<YourPassword>'
auth_source = 'admin' # 認(rèn)證數(shù)據(jù)庫,默認(rèn)是'admin',可以根據(jù)實(shí)際情況修改
# 嘗試連接到MongoDB
try:
client = MongoClient(host, port,
username=username,
password=password,
authSource=auth_source)
print("數(shù)據(jù)庫連接成功")
except Exception as e:
print("數(shù)據(jù)庫連接失敗,原因:", e)四、選擇數(shù)據(jù)庫和集合
在MongoDB中,數(shù)據(jù)存儲在數(shù)據(jù)庫中,每個數(shù)據(jù)庫可以包含多個集合(類似于表)。我們將創(chuàng)建一個名為 mydatabase 的數(shù)據(jù)庫和一個名為 customers 的集合:
# 創(chuàng)建數(shù)據(jù)庫(如果不存在) mydb = client["mydatabase"] print(mydb) # 創(chuàng)建集合 mycol = mydb["customers"] print(mycol)
輸出結(jié)果:
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'mydatabase')
Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'mydatabase'), 'customers')
五、插入數(shù)據(jù)
我們可以使用 insert_one() 和 insert_many() 方法向集合中插入數(shù)據(jù):
# 插入一條數(shù)據(jù)
data = {
"name": "Commas",
"email": "commas@example.com"
}
insert_result = mycol.insert_one(data)
print("Inserted ID:", insert_result.inserted_id)
# 插入多條數(shù)據(jù)
data_list = [ {"name": "CommasKM", "email": "commaskm@example.com"},
{"name": "Kang", "email": "kang@example.com"},
{"name": "Robert", "email": "Robert@example.com"}
]
insert_many_result = mycol.insert_many(data_list)
print("Inserted IDs:", insert_many_result.inserted_ids)輸出結(jié)果:
Inserted ID: 64eb1f52561652f6ae007e52
Inserted IDs: [ObjectId('64eb1f52561652f6ae007e53'), ObjectId('64eb1f52561652f6ae007e54'), ObjectId('64eb1f52561652f6ae007e55')]
六、查詢數(shù)據(jù)
查詢是從集合中檢索數(shù)據(jù)的關(guān)鍵操作,使用 find() 方法可以查詢集合中的數(shù)據(jù)。以下是兩種常見的查詢方法:
查詢所有文檔:
# 查詢所有文檔
all_documents = mycol.find()
print(all_documents)
for document in all_documents:
print(document)
輸出結(jié)果:
<pymongo.cursor.Cursor object at 0x0000025299BEF910>
{'_id': ObjectId('64eb20d6bdc391e33532bda9'), 'name': 'Commas', 'email': 'commas@example.com'}
{'_id': ObjectId('64eb20d6bdc391e33532bdaa'), 'name': 'CommasKM', 'email': 'commaskm@example.com'}
{'_id': ObjectId('64eb20d6bdc391e33532bdab'), 'name': 'Kang', 'email': 'kang@example.com'}
{'_id': ObjectId('64eb20d6bdc391e33532bdac'), 'name': 'Robert', 'email': 'Robert@example.com'}
查詢滿足條件的文檔:
# 查詢滿足條件的文檔
specific_documents = mycol.find({"name": "Commas"})
print(specific_documents)
for document in specific_documents:
print(document)
輸出結(jié)果:
<pymongo.cursor.Cursor object at 0x00000252974F16D0>
{'_id': ObjectId('64eb20d6bdc391e33532bda9'), 'name': 'Commas', 'email': 'commas@example.com'}
七、更新數(shù)據(jù)
要更新數(shù)據(jù),可以使用 update_one() 或 update_many() 方法:
# 更新數(shù)據(jù)
update_query = {"name": "John"}
new_values = {"$set": {"email": "john.new@example.com"}}
mycol.update_one(update_query, new_values)八、刪除數(shù)據(jù)
要刪除數(shù)據(jù),可以使用 delete_one() 或 delete_many() 方法:
# 刪除數(shù)據(jù)
delete_query = {"name": "Alice"}
mycol.delete_one(delete_query)九、斷開連接
在操作完成后,別忘了斷開與數(shù)據(jù)庫的連接:
client.close()
到此這篇關(guān)于Python操作MongoDB的教程分享的文章就介紹到這了,更多相關(guān)Python操作MongoDB內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?通過colorama?設(shè)置控制臺、命令行輸出彩色文字
這篇文章主要介紹了Python?通過colorama?設(shè)置控制臺、命令行輸出彩色文字的相關(guān)資料,需要的朋友可以參考下2023-09-09
python按列索引提取文件夾內(nèi)所有excel指定列匯總(示例代碼)
這篇文章主要介紹了python按列索引提取文件夾內(nèi)所有excel指定列匯總,本文通過多種場景分析結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03
基于Python OpenCV實(shí)現(xiàn)圖像的覆蓋
本文將基于Python、OpenCV和Numpy實(shí)現(xiàn)圖像的覆蓋,即小圖像覆蓋在大圖像上。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-02-02
Python將字符串轉(zhuǎn)換為datetime對象的五種方法
在Python編程中,我們經(jīng)常會遇到需要將字符串形式的日期和時間轉(zhuǎn)換為datetime對象的情況,例如,從文件、數(shù)據(jù)庫或網(wǎng)絡(luò)接口中獲取的數(shù)據(jù)通常是以字符串形式存在的,使用datetime對象會更加方便,所以本文給大家總結(jié)Python將字符串轉(zhuǎn)換為datetime對象的五種方法2025-07-07
python設(shè)置環(huán)境變量的幾種方法總結(jié)
這篇文章主要介紹了在Python中設(shè)置環(huán)境變量可以通過多種方式實(shí)現(xiàn),包括使用os.environ、os.putenv、setuptools以及在操作系統(tǒng)級別設(shè)置,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-01-01
Python的SQLalchemy模塊連接與操作MySQL的基礎(chǔ)示例
SQLalchemy是Python世界中驅(qū)動MySQL的一款高人氣模塊,這里我們從入門開始來看一下Python的SQLalchemy模塊連接與操作MySQL的基礎(chǔ)示例:2016-07-07
詳解python3類型注釋annotations實(shí)用案例
這篇文章主要介紹了詳解python3類型注釋annotations實(shí)用案例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01

