使用Python實現(xiàn)操作mongodb詳解
一、示例
from pymongo import MongoClient from urllib.parse import quote class test_mongo: def __init__(self, host,port,user,pwd,db): self.host = host self.port = port self.user = user self.pwd = pwd self.db = db def build_conn_mongo(self): """ 功能:實現(xiàn)創(chuàng)建客戶端 :return: client """ escaped_username = quote(self.user, safe='') escaped_password = quote(self.pwd, safe='') # 創(chuàng)建客戶端對象,連接MongoDB服務(wù)器 client = MongoClient('mongodb://{0}:{1}@{2}:{3}/{4}'.format(escaped_username, escaped_password, self.host, self.port, self.db)) return client def check_mongo(self,query=None): """ 功能:查詢信息 :param query:輸入查詢條件 eg:{"paId": "38ffefbe29ddcf3c9f574aa"} :return:返回信息,以及獲取查詢的條數(shù) """ client = self.build_conn_mongo() db = client.iot_ota collection = db.集合名稱 results = collection.find(query) count= collection.count_documents(query) client.close() return results,count def update_mongo_by_query(self,query, set_value): """ 功能:按照條件修改一個記錄 :param query:輸入查詢條件 eg:query1 = {"paId": "38ffefbe291a375c4aa"} :param set_value:eg:{"$set":{"description":"yz測試"}} :return:返回基本信息 """ client = self.build_conn_mongo() db = client.iot_ota collection = db.集合名稱 results = collection.update_one(query, set_value) client.close() return results def delete_package_by_query(self,query): """ 功能:按照條件刪除一個記錄 :param query:輸入查詢條件 eg:{"otId":202501221} :return: """ client = self.build_conn_mongo() db = client.iot_ota collection = db.集合名稱 results = collection.delete_one(query) client.close() return results
二、常用指令
序號 | 指令 | 描述 |
---|---|---|
1 | db = client.數(shù)據(jù)庫名 | 獲取數(shù)據(jù)庫 |
2 | db.collection.find() | 篩選所有記錄 |
3 | db.collection.find({“key”:value}) | 按照條件進行查詢記錄 |
4 | db.collection.count_documents(query) | 按照條件查詢符合記錄的條數(shù) |
5 | db.collection.update_one(query, set_value)) | 更新一條記錄 |
6 | db.collection.delete_one(query) | 刪除一條記錄 |
三、遇到的問題
1、轉(zhuǎn)義賬戶和密碼,解決不符合RFC規(guī)范的問題
由于使用賬號和密碼中包含特殊字符出發(fā)點報如下錯誤:
Username and password must be escaped according to RFC 3986, use urllib.parse.quote_plus
解決辦法:
用Python的urllib.parse模塊中的quote函數(shù)來對用戶名和密碼進行轉(zhuǎn)義
2、未指定權(quán)限內(nèi)數(shù)據(jù)庫,導(dǎo)致報權(quán)限錯誤
報錯:pymongo.errors.OperationFailure: Authentication failed具體如下圖
解決辦法:–由于使用的賬戶的權(quán)限只有更db_name的權(quán)限,此處如不指明具體的數(shù)據(jù)庫,則無法訪問client = MongoClient(‘mongodb://{0}:{1}@X.x.x.x:27017/db_name’.format(escaped_username,escaped_password))
3、較新版本的PyMongo中,update和remove方法已經(jīng)被棄用
解決方法:
使用update_one()和update_many()方法來進行單條記錄或多條記錄的更新操作
使用delete_one和delete_many方法來替代remove
到此這篇關(guān)于使用Python實現(xiàn)操作mongodb詳解的文章就介紹到這了,更多相關(guān)Python操作mongodb內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)簡單的ui界面的設(shè)計步驟(適合小白)
當我們書寫一個python程序時,我們在控制臺輸入信息時,往往多有不便,并且為了更加美觀且直觀的方式輸入控制命令,我們常常設(shè)計一個ui界面,這樣就能方便執(zhí)行相關(guān)功能,如計算器、日歷等界面,本博客是為了給ui設(shè)計的小白進行講解,需要的朋友可以參考下2024-07-07Python實現(xiàn)讀取HTML表格 pd.read_html()
這篇文章主要介紹了Python實現(xiàn)讀取HTML表格 pd.read_html(),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07