Python pymongo模塊常用操作分析
本文實例講述了Python pymongo模塊常用操作。分享給大家供大家參考,具體如下:
環(huán)境:pymongo3.0.3,python3
以下是我整理的一些關于pymongo的操作,網上很多是用pymongo.Connecion()
去連接數(shù)據(jù)庫的,但是我這里連接一直提示沒有這個包,如果大家有什么解決方案或者其他需要補充的,也歡迎告訴我。
一、導入pymongo,使用MongClient連接數(shù)據(jù)庫,連接到myinfo數(shù)據(jù)庫
import pymongo client= pymongo.MongoClient("127.0.0.1",27017) db=client.myinfo
二、insert
,insert_one()
只能插入一條數(shù)據(jù),插入多條數(shù)據(jù)的格式是db.user.insert([{條數(shù)1},{條數(shù)2}])
,一定要加[],否則只會添加進去第一條(user是一個集合,除了用db["collection"]外也可以用db.collection
來對集合進行操作
db["user"].insert_one({"name":"zhao"}) db["user"].insert_one({"name":"zhou","age":"5"}) db["user"].insert([{"name":"wu","age":"6"},{"name":"zheng","age":"7"}])
*insert還可以用下面這種方式插入,將數(shù)據(jù)獨立出來
data = [ {"name":"zhao","rank":"1"}, {"name":"qian","rank":"2"}, {"name":"sun","rank":"3"}, {"name":"li","rank":"4"}, ] db.user.insert(data)
三、update,$set:更新操作,multi=True:是否對查詢到的全部數(shù)據(jù)進行操作,upsert=True:如果找不到查詢的結果是否插入一條數(shù)據(jù)
db.user.update_one({"age":"2"},{"$set":{"name":"qian","age":2}}) db.user.update({"name":"sun"},{"$set":{"name":"qian"}},upsert=True)
*update_one也是只能對一條數(shù)據(jù)進行操作,$set是update操作的$操作符,也可以用$inc或$push,前兩個操作速度差不多,$push操作速度較慢。
四、remove,如果后面()內不填寫內容,就是將整個表清空了,db.user.find_one_and_delete()
也是刪除的意思
db.user.remove({"name":"wu"}) db.user.find_one_and_delete({"name":"zheng"})
五、db.user.count()
,統(tǒng)計查詢出的條數(shù),()內不填寫東西,就是統(tǒng)計出該集合下所有的數(shù)據(jù)
print(db.user.count({"age":"6"}))
六、打印出查詢結果
from bson import json_util as jsonb print(jsonb.dumps(list(db.user.find({"name":"wu"})))) print(db.user.find({"name":"wu"}))
可以看到上面兩種方式,不轉換與轉換后的結果對比如下:
*jsonb.dumps()
將查詢出來的結果轉換成了可以讀的list的格式,否則打印出來的是<pymongo.cursor.Cursor object at 0x02096DF0>這種格式的
遍歷col1=db.user.find()
查詢到的所有結果,以及它key=name的value
for i in col1: print(i) print(i["name"])
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)學運算技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python threading Local()函數(shù)用法案例詳解
這篇文章主要介紹了Python threading Local()函數(shù)用法案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-09-09利用python實現(xiàn)聚類分析K-means算法的詳細過程
K-means算法是很典型的基于距離的聚類算法,采用距離作為相似性的評價指標,即認為兩個對象的距離越近,其相似度就越大,下面通過本文給大家介紹利用python實現(xiàn)聚類分析K-means算法的詳細過程,感興趣的朋友一起看看吧2021-11-11Python 中 Selenium 的 getAttribute()
本文將解釋如何使用Selenium的getAttribute()方法,getAttribute() 方法可以檢索元素屬性,例如錨標記的 href 屬性, 該函數(shù)最初將嘗試返回指定屬性的值,感興趣的朋友跟隨小編一起看看吧2023-11-11