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的argpare和click模塊小結(jié)
這篇文章主要介紹了詳解python的argpare和click模塊小結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03matplotlib運(yùn)行時配置(Runtime Configuration,rc)參數(shù)rcParams解析
這篇文章主要介紹了matplotlib運(yùn)行時配置(Runtime Configuration,rc)參數(shù)rcParams解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01Python實(shí)現(xiàn)簡單石頭剪刀布小游戲的示例代碼
石頭剪刀布是一種簡單而又經(jīng)典的游戲,常常用于決定勝負(fù)或者娛樂消遣,本文將使用Python實(shí)現(xiàn)一個簡單的石頭剪刀布游戲,需要的可以參考一下2023-06-06Python實(shí)現(xiàn)刪除文件但保留指定文件
這篇文章主要介紹了Python實(shí)現(xiàn)刪除文件但保留指定文件,本文直接給出實(shí)現(xiàn)代碼,并同時給出代碼解釋,需要的朋友可以參考下2015-06-06python多進(jìn)程及通信實(shí)現(xiàn)異步任務(wù)的方法
這篇文章主要介紹了python多進(jìn)程及通信實(shí)現(xiàn)異步任務(wù)需求,本人也是很少接觸多進(jìn)程的場景,對于python多進(jìn)程的使用也是比較陌生的。在接觸了一些多進(jìn)程的業(yè)務(wù)場景下,對python多進(jìn)程的使用進(jìn)行了學(xué)習(xí),覺得很有必要進(jìn)行一個梳理總結(jié),感興趣的朋友一起看看吧2022-05-05實(shí)例講解Python中函數(shù)的調(diào)用與定義
這篇文章主要介紹了Python中函數(shù)的調(diào)用與定義,是Python入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2016-03-03