亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python操作MongoDB的教程分享

 更新時(shí)間:2023年08月28日 15:54:04   作者:Commas.KM  
MongoDB?是一個(gè)流行的?NoSQL?數(shù)據(jù)庫(kù),以其半結(jié)構(gòu)化的文檔存儲(chǔ)方式而聞名,本文將帶大家逐步了解如何使用Python與MongoDB進(jìn)行交互,從連接到基本操作,快跟隨小編一起學(xué)習(xí)一下吧

一、前言

MongoDB 是一個(gè)流行的 NoSQL 數(shù)據(jù)庫(kù),以其半結(jié)構(gòu)化文檔存儲(chǔ)方式而聞名。Python開發(fā)人員經(jīng)常使用MongoDB來(lái)存儲(chǔ)和處理各種類型的數(shù)據(jù)。本文將帶你逐步了解如何使用Python與MongoDB進(jìn)行交互,從連接到基本操作。

二、安裝MongoDB驅(qū)動(dòng)程序

安裝了MongoDB的Python驅(qū)動(dòng)程序 pymongo

pip install pymongo

三、連接到MongoDB數(shù)據(jù)庫(kù)

首先,確保MongoDB服務(wù)器正在運(yùn)行。

接著,我們?cè)龠B接到MongoDB數(shù)據(jù)庫(kù)。使用 pymongo 庫(kù)的 MongoClient 類來(lái)建立連接:

try:
    client = MongoClient('mongodb://localhost:27017/')
    print("數(shù)據(jù)庫(kù)連接成功")
except Exception as e:
    print("數(shù)據(jù)庫(kù)連接失敗,原因:", e)

可以根據(jù)你的服務(wù)器配置修改連接字符串,如下所示:

# 配置連接信息
host = 'localhost'
port = 27017
username = '<YourUsername>'
password = '<YourPassword>'
auth_source = 'admin'  # 認(rèn)證數(shù)據(jù)庫(kù),默認(rèn)是'admin',可以根據(jù)實(shí)際情況修改
# 嘗試連接到MongoDB
try:
    client = MongoClient(host, port,
                         username=username,
                         password=password,
                         authSource=auth_source)
    print("數(shù)據(jù)庫(kù)連接成功")
except Exception as e:
    print("數(shù)據(jù)庫(kù)連接失敗,原因:", e)

四、選擇數(shù)據(jù)庫(kù)和集合

在MongoDB中,數(shù)據(jù)存儲(chǔ)在數(shù)據(jù)庫(kù)中,每個(gè)數(shù)據(jù)庫(kù)可以包含多個(gè)集合(類似于表)。我們將創(chuàng)建一個(gè)名為 mydatabase 的數(shù)據(jù)庫(kù)和一個(gè)名為 customers 的集合:

# 創(chuàng)建數(shù)據(jù)庫(kù)(如果不存在)
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ù)

要?jiǎng)h除數(shù)據(jù),可以使用 delete_one() delete_many() 方法:

# 刪除數(shù)據(jù)
delete_query = {"name": "Alice"}
mycol.delete_one(delete_query)

九、斷開連接

在操作完成后,別忘了斷開與數(shù)據(jù)庫(kù)的連接:

client.close()

到此這篇關(guān)于Python操作MongoDB的教程分享的文章就介紹到這了,更多相關(guān)Python操作MongoDB內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論