Python常見MongoDB數(shù)據(jù)庫操作實(shí)例總結(jié)
本文實(shí)例講述了Python常見MongoDB數(shù)據(jù)庫操作。分享給大家供大家參考,具體如下:
MongoDB 是一個(gè)基于分布式文件存儲(chǔ)的數(shù)據(jù)庫。由C++語言編寫。旨在為WEB應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲(chǔ)解決方案。
MongoDB 是一個(gè)介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫的。他支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似json的bson格式,因此可以存儲(chǔ)比較復(fù)雜的數(shù)據(jù)類型。Mongo最大的特點(diǎn)是他支持的查詢語言非常強(qiáng)大,其語法有點(diǎn)類似于面向?qū)ο蟮牟樵冋Z言,幾乎可以實(shí)現(xiàn)類似關(guān)系數(shù)據(jù)庫單表查詢的絕大部分功能。接下來記錄一下在使用PyMongo操作MongoDB
下載pymongo庫
pip install pymongo
前置操作
# 獲取MongoDB操作,localhost為host,27017為MongoDB默認(rèn)port client = pymongo.MongoClient("mongodb://localhost:27017/") # 操作test數(shù)據(jù)庫 db = client.test # 獲取Student集合 student = db.Student
插入單條數(shù)據(jù)
# 插入一條數(shù)據(jù),并獲取返回結(jié)果 res = student.insert_one({"name":"老王"}) # 獲取插入之后該條數(shù)據(jù)的id object_id = res.inserted_id print(object_id)
插入多條數(shù)據(jù)
# 插入9條數(shù)據(jù) res = student.insert_many([{"name":"name%d"%index} for index in range(1,10)]) # 獲取插入之后該9條數(shù)據(jù)的ids,object_ids為一個(gè)list object_ids = res.inserted_ids print(object_ids)
查詢單條數(shù)據(jù)
# 查詢單條數(shù)據(jù),res為一個(gè)dict res = student.find_one({"name":"老王"})
查詢滿足條件的所有數(shù)據(jù)
# 查詢滿足條件的所有數(shù)據(jù),res為一個(gè)pymongo.cursor.Cursor對(duì)象 res = student.find({"name":"老王"}) # 獲取數(shù)據(jù)個(gè)數(shù) print(res.count()) for index in res: # index為一個(gè)dict。注意:這個(gè)循環(huán)只能進(jìn)行一次,如需再次操作返回結(jié)果,需要在find一次,或?qū)ist(res),將這個(gè)返回結(jié)果保存起來 print(index)
更新
# 查詢并更新。{"name":"老王"}為查詢條件;{"$set":{"addr":"家住隔壁"}}更新數(shù)據(jù);upsert=False找不到不插入數(shù)據(jù),upsert=True找不到則插入數(shù)據(jù) # res為返回結(jié)果,res為一個(gè)字典對(duì)象,是之前數(shù)據(jù)的字典 res = student.find_one_and_update({"name":"老王"},{"$set":{"addr":"家住隔壁"}},upsert=False)
刪除單條數(shù)據(jù)
student.delete_one({"name":"老王"})
刪除匹配條件的所有數(shù)據(jù)
student.delete_many({"name":"老王"})
附:更多MongoDB的操作
MongoDB 是一個(gè)基于分布式文件存儲(chǔ)的數(shù)據(jù)庫。由C++語言編寫。旨在為WEB應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲(chǔ)解決方案。
MongoDB 是一個(gè)介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫的。他支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似json的bson格式,因此可以存儲(chǔ)比較復(fù)雜的數(shù)據(jù)類型。Mongo最大的特點(diǎn)是他支持的查詢語言非常強(qiáng)大,其語法有點(diǎn)類似于面向?qū)ο蟮牟樵冋Z言,幾乎可以實(shí)現(xiàn)類似關(guān)系數(shù)據(jù)庫單表查詢的絕大部分功能。接下來記錄一下在終端怎么使用MongoDB:
常用命令
切換/創(chuàng)建數(shù)據(jù)庫
use xxx; # 切換數(shù)據(jù)庫,不存在則創(chuàng)建
插入數(shù)據(jù)
# 插入數(shù)據(jù),name="Python",age=100,Student為集合(表)名,Student不存在會(huì)自動(dòng)創(chuàng)建 db.Student.insert({name:"Python",age:100})
或者定義一個(gè)字典
document = {name:"Python",age:100} db.Student.insert(document)
查詢數(shù)據(jù)
# 查詢所有數(shù)據(jù) db.Student.find() # 查詢所有數(shù)據(jù)并格式化輸出 db.Student.find().pretty() # 條件查詢,name="python"的所有數(shù)據(jù) db.Student.find({name:"python"}) # 條件查詢,age > 50的所有數(shù)據(jù) db.Student.find({age:{$gt:50}}) # 條件查詢,age >= 50的所有數(shù)據(jù) db.Student.find({age:{$gte:50}}) # 條件查詢,age < 50的所有數(shù)據(jù) db.Student.find({age:{$lt:50}}) # 條件查詢,age <= 50的所有數(shù)據(jù) db.Student.find({age:{$lte:50}}) # 條件查詢,age == 50的所有數(shù)據(jù) db.Student.find({age:{$eq:50}}) # 條件查詢,age != 50的所有數(shù)據(jù) db.Student.find({age:{$ne:50}}) # 條件查詢,存在name字段的所有數(shù)據(jù) db.Student.find({name:{$exists:true}}) # 多條件查詢,name="python"并且age=50的所有數(shù)據(jù) db.Student.find({name:"python",age:50}) # $and語法,name="python"并且age=50的所有數(shù)據(jù)。 db.Student.find({$and:[{name:"python"},{age:50}]}) # 查詢字典數(shù)組的數(shù)據(jù)infoList = [{"province":"廣東","city":"深圳"}] db.Student.find({"infoList.province":"廣東"}) # 查詢數(shù)量 db.Student.find({name:"python"}).count() # 或查詢,$or語法。查詢name="python"或name="android"的所有數(shù)據(jù) db.Student.find({$or:[{name:"python"},{name:"android"}]}) # $size語法,查詢info數(shù)組長度為8的所有數(shù)據(jù) db.Student.find({info:{$size:8}}) # $not語法,查詢info數(shù)組長度不為8的所有數(shù)據(jù) db.Student.find({info:{$not:{$size:8}}}) # and與or聯(lián)合使用.相當(dāng)于 where age=18 and (name="python" or name="android") db.Student.find({age:18,$or:[{name:"python"},{name:"android"}]}) # $nor語法,搜索name既不等于"python"且不等于"android"的所有數(shù)據(jù) db.Student.find({"$nor":[{name:"python"},{name:"android"}]}) # $in語法.搜索name="老張"或name="老王"的所有數(shù)據(jù) db.Student.find({name:{$in:["老王","老張"]}}) # $nin語法.搜索name不為"老張"或"老王"的所有數(shù)據(jù) db.Student.find({name:{$nin:["老王","老張"]}}) # $all語法,搜索info=["aaa","bbb"]的所有數(shù)據(jù) db.Student.find({info:{$all:["aaa","bbb"]}}) # $mod語法,搜索sex % 2 == 0的所有數(shù)據(jù) db.Student.find({sex:{$mod:[2,0]}}) # $where語法,搜索age=info的所有數(shù)據(jù) db.Student.find({"$where":"this.age==this.info"}) # $slice語法,過濾,info數(shù)組中的后3個(gè)數(shù)據(jù) db.Student.find({},{info:{$slice:-3}}) # $slice語法,過濾,info數(shù)組中的前3個(gè)數(shù)據(jù) db.Student.find({},{info:{$slice:3}}) # $slice語法,過濾,info數(shù)組中跳過20個(gè)數(shù)據(jù)之后取10個(gè)數(shù)據(jù) db.Student.find({},{info:{$slice:[20,10]}}) # $slice語法,過濾,info數(shù)組中倒數(shù)第20個(gè)數(shù)據(jù)之后取10個(gè)數(shù)據(jù) db.Student.find({},{info:{$slice:[-20,10]}}) # 正則.獲取name包含"王"的所有數(shù)據(jù) db.Student.find({name:{$regex:"王"}}) # 正則。獲取name包含"a"并且不區(qū)分大小寫的所有數(shù)據(jù) db.Student.find({name:{$regex:"a",$options:"i"}})
更新數(shù)據(jù)
# 找到name="MongoDB"的數(shù)據(jù),將其更改為name="MongoDB學(xué)習(xí)",只修改匹配到的第一條數(shù)據(jù) db.Student.update({name:"MongoDB"},{$set:{name:"MongoDB學(xué)習(xí)"}}) # 找不到name="MongoDB"的數(shù)據(jù),則插入name="MongoDB學(xué)習(xí)",找到了則為修改。upsert:true找不到則插入,默認(rèn)false,不插入 db.Student.update({name:"MongoDB"},{$set:{name:"MongoDB學(xué)習(xí)"}},{upsert:true}) # 找到name="MongoDB"的數(shù)據(jù),將其更改為name="MongoDB學(xué)習(xí)"。multi:true更改所有匹配的數(shù)據(jù),默認(rèn)false,只匹配第一條 db.Student.update({name:"MongoDB"},{$set:{name:"MongoDB學(xué)習(xí)"}},{multi:true}) # 匹配name="MongoDB"的第一條數(shù)據(jù),將其更改為name="MongoDB學(xué)習(xí)" db.Student.updateOne({name:"MongoDB"},{$set:{name:"MongoDB學(xué)習(xí)"}}) # 更新字典數(shù)組的數(shù)據(jù)infoList = [{"province":"廣東","city":"深圳"}] db.Student.update({"infoList.province":"廣東"},{"$set":{"province.$.city":"廣州"}}) # 將age>18的數(shù)據(jù),修改name="xxx",第一個(gè)false:不存在不會(huì)插入(true為不存在則插入),第二個(gè)false:只匹配第一條數(shù)據(jù)(true為匹配所有數(shù)據(jù)) db.Student.update({age:{$gt:18}},{$set:{name:"xxx"}},false,false) # 在name="python"的所有數(shù)據(jù)里,將age字段值+1 db.Student.update({name:"python"},{$inc:{age:1}}) # 在name="python"的所有數(shù)據(jù)里,將age鍵刪除,1可以是任何值 db.Student.update({name:"python"},{$unset:{age:1}}) # 在name="python"的所有數(shù)據(jù)里,將age鍵名修改成"Age" db.Student.update({name:"python"},{$rename:{age:"Age"}}) # 在name="python"的所有數(shù)據(jù)里,在名為array的數(shù)組添加abc元素 db.Student.update({name:"python"},{$push:{array:"abc"}}) # 在name="python"的所有數(shù)據(jù)里,將["abc","adc"]里所有元素添加到array里面 db.Student.update({name:"python"},{$pushAll:{array:["abc","adc"]}}) # 在name="python"的所有數(shù)據(jù)里,在名為array的數(shù)組刪除abc元素 db.Student.update({name:"python"},{$pull:{array:"abc"}}) # 在name="python"的所有數(shù)據(jù)里,將["abc","adc"]里所有元素全部從array里刪除 db.Student.update({name:"python"},{$pullAll:{array:["abc","adc"]}}) # 在name="python"的所有數(shù)據(jù)里,刪除array數(shù)組尾部數(shù)據(jù),無論array為多少都只刪除一條,array小于0時(shí),刪除頭部第一條,array大于等于0時(shí),刪除尾部第一條 db.Student.update({name:"python"},{$pop:{array:2}})
刪除數(shù)據(jù)
# 刪除匹配到的所有數(shù)據(jù) db.Student.remove({name:"老張"}) # 刪除匹配到第一條數(shù)據(jù),justOne:true只刪除一條數(shù)據(jù) db.Student.remove({name:"老張"},{justOne:true})
**type**:type**:type操作符是基于BSON類型來檢索集合中匹配的數(shù)據(jù)類型,并返回結(jié)果
常用type類型:
數(shù)字 | 類型 |
---|---|
1 | Double |
2 | String |
3 | Object |
4 | Array |
5 | Binary data |
6 | Undefined |
7 | Object id |
8 | Boolean |
9 | Date |
10 | Null |
11 | Regular Expression |
13 | JavaScript |
14 | Symbol |
15 | JavaScript (with scope) |
16 | 32-bit integer |
17 | Timestamp |
18 | 64-bit integer |
255 | Min key |
127 | Max key |
# 查詢name為String類型的所有數(shù)據(jù),2為String db.Student.find({name:{$type:2}})
- limit:限制條數(shù)
# 查詢name="python"的所有數(shù)據(jù),限制2條 db.Student.find({name:"python"}).limit(2)
- skip:跳過數(shù)據(jù)
# 查詢name > 15的數(shù)據(jù),跳過前兩條,并限制只查詢兩條 db.Student.find({name:{$gt:15}}).limit(2).skip(2)
- sort:排序,1位升序,-1位降序
# 查詢所有數(shù)據(jù),并以age升序排列 db.Student.find().sort({age:1}) # 多條件排序 db.Student.find().sort({age:1,score:-1})
- findAndModify:查找并更新
# 查找name="python"的所有數(shù)據(jù),并修改age=18 db.Student.findAndModify({query:{name:"python"},update:{$set:{age:18}}})
- ObjectId
# 獲取文檔的創(chuàng)建時(shí)間 ObjectId("598542475e6b2464187abef7").getTimestamp()
- aggregate:聚合查詢
常用聚合表達(dá)式:
表達(dá)式 | 描述 |
---|---|
$sum | 和 |
$avg | 平均值 |
$min | 最小值 |
$max | 最大值 |
$push | 在結(jié)果中插入值到數(shù)組中 |
$addToSet | 在結(jié)果中插入值到數(shù)組中,但不創(chuàng)建副本 |
$first | 根據(jù)資源文檔的排序,獲取第一個(gè)數(shù)據(jù) |
$last | 根據(jù)資源文檔的排序,獲取最后一個(gè)數(shù)據(jù) |
# 根據(jù)name分組,并插入sum,sum值為該組所有age的和 db.Student.aggregate([{$group:{_id:"$name",sum:{$sum:"$age"}}}]) # 根據(jù)name分組,并插入sum,sum值為該組的數(shù)量,并以sum排序,升序 db.Student.aggregate([{$group:{_id:"$name",sum:{$sum:1}}}]) # 根據(jù)name分組,并插入avg,avg值為該組所有age的平均值 db.Student.aggregate([{$group:{_id:"$name",avg:{$avg:"$age"}}}]) # 根據(jù)name分組,并插入min,min值為該組所有age的最小值 db.Student.aggregate([{$group:{_id:"$name",min:{$min:"$age"}}}]) # 根據(jù)name分組,并插入max,max值為該組所有age的最大值 db.Student.aggregate([{$group:{_id:"$name",max:{$max:"$age"}}}]) # 根據(jù)name分組,并插入數(shù)組array,array值為該組所有的age值 db.Student.aggregate([{$group:{_id:"$name",array:{$push:"$age"}}}]) # 根據(jù)name分組,并插入數(shù)組array,array值為該組所有的age值 db.Student.aggregate([{$group:{_id:"$name",array:{$addToSet:"$age"}}}]) # 根據(jù)name分組,并插入f,f值為該組age下的第一個(gè)值 db.Student.aggregate([{$group:{_id:"$name",f:{$first:"$age"}}}]) # 根據(jù)name分組,并插入l,l值為該組age下的第一個(gè)值 db.Student.aggregate([{$group:{_id:"$name",l:{$last:"$age"}}}])
管道操作實(shí)例
1. $project:用于修改文檔的輸出結(jié)構(gòu)
# 查詢所有的name,age數(shù)據(jù),默認(rèn)包含_id數(shù)據(jù)。讓不包含_id,可以使_id:0 db.Student.aggregate({$project:{name:1,age:1}})
此時(shí)輸出的內(nèi)容只有_id,name,age,_id是默認(rèn)會(huì)輸出的,想不輸出_id,可以使_id:0
2. $match:用于過濾數(shù)據(jù)
db.Student.aggregate([{$match:{age:{$gt:19,$lte:23}}},{$group:{_id:null,count:{$sum:1}}}])
match過濾出age大于19且小于等于23的數(shù)據(jù),然后將符合條件的記錄送到下一階段match過濾出age大于19且小于等于23的數(shù)據(jù),然后將符合條件的記錄送到下一階段group管道操作符進(jìn)行處理
3. $skip:將前5個(gè)過濾掉
db.Student.aggregate({$skip:5})
$skip將前面5個(gè)數(shù)據(jù)過濾掉
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- python連接mongodb操作數(shù)據(jù)示例(mongodb數(shù)據(jù)庫配置類)
- Python的MongoDB模塊PyMongo操作方法集錦
- Python中的MongoDB基本操作:連接、查詢實(shí)例
- 在Python中使用mongoengine操作MongoDB教程
- 使用Python腳本操作MongoDB的教程
- python操作MongoDB基礎(chǔ)知識(shí)
- 詳解Python3操作Mongodb簡明易懂教程
- Python操作mongodb數(shù)據(jù)庫進(jìn)行模糊查詢操作示例
- Python 操作 MongoDB 講解詳細(xì)
- Python操作MongoDB的實(shí)現(xiàn)示例
相關(guān)文章
Python基于DFA算法實(shí)現(xiàn)內(nèi)容敏感詞過濾
DFA?算法是通過提前構(gòu)造出一個(gè)?樹狀查找結(jié)構(gòu),之后根據(jù)輸入在該樹狀結(jié)構(gòu)中就可以進(jìn)行非常高效的查找。本文將利用改算法實(shí)現(xiàn)敏感詞過濾,需要的可以參考一下2022-04-04Python中Turtle庫改變畫筆(海龜)方向的兩種方法總結(jié)
turtle庫是python標(biāo)準(zhǔn)庫之一,入門級(jí)繪圖庫,import turtle之后即可使用,下面這篇文章主要給大家介紹了關(guān)于Python中Turtle庫改變畫筆(海龜)方向的兩種方法,需要的朋友可以參考下2022-11-11Blender Python編程實(shí)現(xiàn)程序化建模生成超形示例詳解
這篇文章主要為大家介紹了Blender Python編程實(shí)現(xiàn)程序化建模生成超形示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08pytest自定義命令行參數(shù)的實(shí)現(xiàn)
本文主要介紹了在使用pytest運(yùn)行測試用例時(shí),通過傳遞自定義命令行參數(shù)來啟動(dòng)mitmdump進(jìn)程進(jìn)行抓包,具有一定的參考價(jià)值,感興趣的可以了解一下2024-12-12淺談python中的__init__、__new__和__call__方法
這篇文章主要給大家介紹了關(guān)于python中__init__、__new__和__call__方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考學(xué)習(xí),下面來跟著小編一起看看吧。2017-07-07python實(shí)現(xiàn)報(bào)表自動(dòng)化詳解
這篇文章主要介紹了python實(shí)現(xiàn)報(bào)表自動(dòng)化詳解,涉及python讀,寫excel—xlwt常用功能,xlutils 常用功能,xlwt寫Excel時(shí)公式的應(yīng)用等相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11tensorflow實(shí)現(xiàn)對(duì)張量數(shù)據(jù)的切片操作方式
今天小編就為大家分享一篇tensorflow實(shí)現(xiàn)對(duì)張量數(shù)據(jù)的切片操作方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01