爬蟲系列之mongodb

mongodb

mongo簡介

簡介

MongoDB是一個基於分佈式文件存儲的數據庫。由C++語言編寫。旨在爲WEB應用提供可擴展的高性能數據存儲解決方案。
MongoDB是一個介於關係數據庫和非關係數據庫之間的產品,是非關係數據庫當中功能最豐富,最像關係數據庫的。它支持的數據結構很是鬆散,是相似json的bson格式,所以能夠存儲比較複雜的數據類型。Mongo最大的特色是它支持的查詢語言很是強大,其語法有點相似於面向對象的查詢語言,幾乎能夠實現相似關係數據庫單表查詢的絕大部分功能,並且還支持對數據創建索引。html

下載安裝

downloadpython

mongodb的優點

mongodb的CURD

數據庫操做

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
> use blog
switched to db blog
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
> db.article.insert({ "title" : "西遊記" })
WriteResult({ "nInserted" : 1 })
> db.userinfo.insert({ "name" : "alex" })
WriteResult({ "nInserted" : 1 })
> show tables;
article
userinfo
> show dbs
admin 0.000GB
blog 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
> db.dropDatabase()
{ "dropped" : "blog" , "ok" : 1 }  

集合操做

?
1
2
3
4
5
6
7
8
9
10
11
12
> use blog
switched to db blog
> db.article.insert({ "title" : "python" })
WriteResult({ "nInserted" : 1 })
> db.article.insert({ "title" : "linux" })
WriteResult({ "nInserted" : 1 })
> show tables;
article
> db.article.drop()
true
> show tables;
>

文檔操做

添加文檔

複製代碼
#一、沒有指定_id則默認ObjectId,_id不能重複,且在插入後不可變
 
#二、插入單條
user0={
    "name":"egon",
    "age":10,
    'hobbies':['music','read','dancing'],
    'addr':{
        'country':'China',
        'city':'BJ'
    }
}
 
db.test.insert(user0)
db.test.find()
 
#三、插入多條
user1={
    "_id":1,
    "name":"alex",
    "age":10,
    'hobbies':['music','read','dancing'],
    'addr':{
        'country':'China',
        'city':'weifang'
    }
}
 
user2={
    "_id":2,
    "name":"wupeiqi",
    "age":20,
    'hobbies':['music','read','run'],
    'addr':{
        'country':'China',
        'city':'hebei'
    }
}
 
 
user3={
    "_id":3,
    "name":"yuanhao",
    "age":30,
    'hobbies':['music','drink'],
    'addr':{
        'country':'China',
        'city':'heibei'
    }
}
 
user4={
    "_id":4,
    "name":"jingliyang",
    "age":40,
    'hobbies':['music','read','dancing','tea'],
    'addr':{
        'country':'China',
        'city':'BJ'
    }
}
 
user5={
    "_id":5,
    "name":"jinxin",
    "age":50,
    'hobbies':['music','read',],
    'addr':{
        'country':'China',
        'city':'henan'
    }
}
db.user.insertMany([user1,user2,user3,user4,user5]) 
db.user.find()
複製代碼

查看文檔

複製代碼
###################### (1) 比較運算  ###################################
 
# SQL:=,!=,>,<,>=,<=
# MongoDB:{key:value}表明什麼等於什麼,"$ne","$gt","$lt","gte","lte",其中"$ne"能用於全部數據類型
 
#一、select * from db1.user where name = "alex";
db.user.find({'name':'alex'})
 
#二、select * from db1.user where name != "alex";
db.user.find({'name':{"$ne":'alex'}})
 
#三、select * from db1.user where id > 2;
db.user.find({'_id':{'$gt':2}})
 
#四、select * from db1.user where id < 3;
db.user.find({'_id':{'$lt':3}})
 
#五、select * from db1.user where id >= 2;
db.user.find({"_id":{"$gte":2,}})
 
#六、select * from db1.user where id <= 2;
db.user.find({"_id":{"$lte":2}})

###################### (2) 邏輯運算  ###################################
 
# SQL:and,or,not
# MongoDB:字典中逗號分隔的多個條件是and關係,"$or"的條件放到[]內,"$not"
 
#一、select * from db1.user where id >= 2 and id < 4;
db.user.find({'_id':{"$gte":2,"$lt":4}})
 
#二、select * from db1.user where id >= 2 and age < 40;
db.user.find({"_id":{"$gte":2},"age":{"$lt":40}})
 
#三、select * from db1.user where id >= 5 or name = "alex";
db.user.find({
    "$or":[
        {'_id':{"$gte":5}},
        {"name":"alex"}
        ]
})
#四、select * from db1.user where id % 2=1;
db.user.find({'_id':{"$mod":[2,1]}})
 
#五、上題,取反
db.user.find({'_id':{"$not":{"$mod":[2,1]}}})
###################### (3) 成員運算  ###################################
 
# SQL:in,not in
# MongoDB:"$in","$nin"
 
#一、select * from db1.user where age in (20,30,31);
db.user.find({"age":{"$in":[20,30,31]}})
 
#二、select * from db1.user where name not in ('alex','yuanhao');
db.user.find({"name":{"$nin":['alex','yuanhao']}})

###################### (4) 正則匹配  ###################################
 
# SQL: regexp 正則
# MongoDB: /正則表達/i
 
#一、select * from db1.user where name regexp '^j.*?(g|n)$';
db.user.find({'name':/^j.*?(g|n)$/i})


###################### (5) 取指定字段  ###################################
 
#一、select name,age from db1.user where id=3;
db.user.find({'_id':3},{''name':1,'age':1})
#2 db.user.find({'_id':3},{"addr":0})
{ "_id" : 3, "name" : "yuanhao", "age" : 30, "hobbies" : [ "music", "drink" ] }

###################### (6) 查詢數組  ###################################
 
#一、查看有dancing愛好的人
db.user.find({'hobbies':'dancing'})
 
#二、查看既有dancing愛好又有tea愛好的人
db.user.find({
    'hobbies':{
        "$all":['dancing','tea']
        }
})
 
#三、查看第4個愛好爲tea的人
db.user.find({"hobbies.3":'tea'})
 
#四、查看全部人最後兩個愛好
db.user.find({},{'hobbies':{"$slice":-2},"age":0,"_id":0,"name":0,"addr":0})
 
#五、查看全部人的第2個到第3個愛好
db.user.find({},{'hobbies':{"$slice":[1,2]},"age":0,"_id":0,"name":0,"addr":0})
 

###################### (7) 排序  ###################################
 
# 排序:--1表明升序,-1表明降序
db.user.find().sort({"name":1,})
db.user.find().sort({"age":-1,'_id':1})

###################### (8) 分頁  ###################################
 
# 分頁:--limit表明取多少個document,skip表明跳過前多少個document。
db.user.find().sort({'age':1}).limit(1).skip(2)
 
###################### (9) 查詢數量  ###################################
# 獲取數量
db.user.count({'age':{"$gt":30}})
 
--或者
db.user.find({'age':{"$gt":30}}).count()

###################### (10) 其它  ###################################
 
#一、{'key':null} 匹配key的值爲null或者沒有這個key
db.t2.insert({'a':10,'b':111})
db.t2.insert({'a':20})
db.t2.insert({'b':null})
 
> db.t2.find({"b":null})
{ "_id" : ObjectId("5a5cc2a7c1b4645aad959e5a"), "a" : 20 }
{ "_id" : ObjectId("5a5cc2a8c1b4645aad959e5b"), "b" : null }
 
#二、查找全部
db.user.find() #等同於db.user.find({})
db.user.find().pretty()
 
#三、查找一個,與find用法一致,只是只取匹配成功的第一個
db.user.findOne({"_id":{"$gt":3}}) 
複製代碼

修改文檔

複製代碼
############################## 1 update的語法  ##############################
 
update() 方法用於更新已存在的文檔。語法格式以下:
db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)
參數說明:對比update db1.t1 set name='EGON',sex='Male' where name='egon' and age=18;
 
query : 至關於where條件。
update : update的對象和一些更新的操做符(如$,$inc...等,至關於set後面的
upsert : 可選,默認爲false,表明若是不存在update的記錄不更新也不插入,設置爲true表明插入。
multi : 可選,默認爲false,表明只更新找到的第一條記錄,設爲true,表明更新找到的所有記錄。
writeConcern :可選,拋出異常的級別。
 
更新操做是不可分割的:若兩個更新同時發送,先到達服務器的先執行,而後執行另一個,不會破壞文檔。
 
############################## 2 覆蓋更新  ##############################
 
#注意:除非是刪除,不然_id是始終不會變的
#1 :
db.user.update({'age':20},{"name":"Wxx","hobbies_count":3})
是用{"_id":2,"name":"Wxx","hobbies_count":3}覆蓋原來的記錄
 
#二、一種最簡單的更新就是用一個新的文檔徹底替換匹配的文檔。這適用於大規模式遷移的狀況。例如
var obj=db.user.findOne({"_id":2})
 
obj.username=obj.name+'SB'
obj.hobbies_count++
delete obj.age
 
db.user.update({"_id":2},obj)
 
############################## 3 局部更新  ##############################
 
#設置:$set
 
一般文檔只會有一部分須要更新。可使用原子性的更新修改器,指定對文檔中的某些字段進行更新。
更新修改器是種特殊的鍵,用來指定複雜的更新操做,好比修改、增長後者刪除
 
#一、update db1.user set  name="WXX" where id = 2
db.user.update({'_id':2},{"$set":{"name":"WXX",}})
 
#二、沒有匹配成功則新增一條{"upsert":true}
db.user.update({'_id':6},{"$set":{"name":"egon","age":18}},{"upsert":true})
 
#三、默認只改匹配成功的第一條,{"multi":改多條}
db.user.update({'_id':{"$gt":4}},{"$set":{"age":28}})
db.user.update({'_id':{"$gt":4}},{"$set":{"age":38}},{"multi":true})
 
#四、修改內嵌文檔,把名字爲alex的人所在的地址國家改爲Japan
db.user.update({'name':"alex"},{"$set":{"addr.country":"Japan"}})
 
#五、把名字爲alex的人的地2個愛好改爲piao
db.user.update({'name':"alex"},{"$set":{"hobbies.1":"piao"}})
 
#六、刪除alex的愛好,$unset
db.user.update({'name':"alex"},{"$unset":{"hobbies":""}})
 
############################## 4 自增或自減  ##############################
 
#增長和減小:$inc
 
#一、全部人年齡增長一歲
db.user.update({},
    {
        "$inc":{"age":1}
    },
    {
        "multi":true
    }
    )
#二、全部人年齡減小5歲
db.user.update({},
    {
        "$inc":{"age":-5}
    },
    {
        "multi":true
    }
    )
 
 
############################## 5 添加刪除數組內元素 ##############################
 
#添加刪除數組內元素:$push,$pop,$pull
     
往數組內添加元素:$push
#一、爲名字爲yuanhao的人添加一個愛好read
db.user.update({"name":"yuanhao"},{"$push":{"hobbies":"read"}})
 
#二、爲名字爲yuanhao的人一次添加多個愛好tea,dancing
db.user.update({"name":"yuanhao"},{"$push":{
    "hobbies":{"$each":["tea","dancing"]}
}})
 
按照位置且只能從開頭或結尾刪除元素:$pop
#三、{"$pop":{"key":1}} 從數組末尾刪除一個元素
 
db.user.update({"name":"yuanhao"},{"$pop":{
    "hobbies":1}
})
 
#四、{"$pop":{"key":-1}} 從頭部刪除
db.user.update({"name":"yuanhao"},{"$pop":{
    "hobbies":-1}
})
 
#五、按照條件刪除元素,:"$pull" 把符合條件的通通刪掉,而$pop只能從兩端刪
db.user.update({'addr.country':"China"},{"$pull":{
    "hobbies":"read"}
},
{
    "multi":true
}
)
 
 
############################## 6 避免重複添加 ##############################
 
#避免添加劇復:"$addToSet"
 
db.urls.insert({"_id":1,"urls":[]})
 
db.urls.update({"_id":1},{"$addToSet":{"urls":'http://www.baidu.com'}})
db.urls.update({"_id":1},{"$addToSet":{"urls":'http://www.baidu.com'}})
db.urls.update({"_id":1},{"$addToSet":{"urls":'http://www.baidu.com'}})
 
db.urls.update({"_id":1},{
    "$addToSet":{
        "urls":{
        "$each":[
            'http://www.baidu.com',
            'http://www.baidu.com',
            'http://www.xxxx.com'
            ]
            }
        }
    }
)
 
############################## 7 其它 ##############################
 
#一、瞭解:限制大小"$slice",只留最後n個
 
db.user.update({"_id":5},{
    "$push":{"hobbies":{
        "$each":["read",'music','dancing'],
        "$slice":-2
    }
    }
})
 
#二、瞭解:排序The $sort element value must be either 1 or -1"
db.user.update({"_id":5},{
    "$push":{"hobbies":{
        "$each":["read",'music','dancing'],
        "$slice":-1,
        "$sort":-1
    }
    }
})
 
#注意:不能只將"$slice"或者"$sort"與"$push"配合使用,且必須使用"$eah"  
複製代碼

刪除文檔

?
1
2
3
4
5
6
7
8
#一、刪除多箇中的第一個
db.user.deleteOne({ 'age' : 8 })
  
#二、刪除國家爲China的所有
db.user.deleteMany( { 'addr.country' : 'China' } )
  
#三、刪除所有
db.user.deleteMany({})

pymongo

複製代碼
"""
MongoDB存儲
    在這裏咱們來看一下Python3下MongoDB的存儲操做,在本節開始以前請確保你已經安裝好了MongoDB並啓動了其服務,另外安裝好了Python
    的PyMongo庫。
  
鏈接MongoDB
    鏈接MongoDB咱們須要使用PyMongo庫裏面的MongoClient,通常來講傳入MongoDB的IP及端口便可,第一個參數爲地址host,
    第二個參數爲端口port,端口若是不傳默認是27017。
"""<br>
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)<br>
"""
這樣咱們就能夠建立一個MongoDB的鏈接對象了。另外MongoClient的第一個參數host還能夠直接傳MongoDB的鏈接字符串,以mongodb開頭,
例如:client = MongoClient('mongodb://localhost:27017/')能夠達到一樣的鏈接效果。<br>
"""
# 指定數據庫
# MongoDB中還分爲一個個數據庫,咱們接下來的一步就是指定要操做哪一個數據庫,在這裏我以test數據庫爲例進行說明,因此下一步咱們
# 須要在程序中指定要使用的數據庫。
  
db = client.test
# 調用client的test屬性便可返回test數據庫,固然也能夠這樣來指定:
# db = client['test']
# 兩種方式是等價的。
  
# 指定集合
# MongoDB的每一個數據庫又包含了許多集合Collection,也就相似與關係型數據庫中的表,下一步咱們須要指定要操做的集合,
# 在這裏咱們指定一個集合名稱爲students,學生集合。仍是和指定數據庫相似,指定集合也有兩種方式。
  
collection = db.students
# collection = db['students']
# 插入數據,接下來咱們即可以進行數據插入了,對於students這個Collection,咱們新建一條學生數據,以字典的形式表示:
  
student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
# 在這裏咱們指定了學生的學號、姓名、年齡和性別,而後接下來直接調用collection的insert()方法便可插入數據。
  
result = collection.insert(student)
print(result)
# 在MongoDB中,每條數據其實都有一個_id屬性來惟一標識,若是沒有顯式指明_id,MongoDB會自動產生一個ObjectId類型的_id屬性。
# insert()方法會在執行後返回的_id值。
  
# 運行結果:
# 5932a68615c2606814c91f3d
# 固然咱們也能夠同時插入多條數據,只須要以列表形式傳遞便可,示例以下:
  
student1 = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
  
student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}
  
result = collection.insert([student1, student2])
print(result)
# 返回的結果是對應的_id的集合,運行結果:
# [ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]
# 實際上在PyMongo 3.X版本中,insert()方法官方已經不推薦使用了,固然繼續使用也沒有什麼問題,
# 官方推薦使用insert_one()和insert_many()方法將插入單條和多條記錄分開。
  
student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
  
result = collection.insert_one(student)
print(result)
print(result.inserted_id)
# 運行結果:
# <pymongo.results.InsertOneResult object at 0x10d68b558>
# 5932ab0f15c2606f0c1cf6c5
# 返回結果和insert()方法不一樣,此次返回的是InsertOneResult對象,咱們能夠調用其inserted_id屬性獲取_id。
  
# 對於insert_many()方法,咱們能夠將數據以列表形式傳遞便可,示例以下:
  
student1 = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
  
student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}
  
result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)
# insert_many()方法返回的類型是InsertManyResult,調用inserted_ids屬性能夠獲取插入數據的_id列表,運行結果:
  
# <pymongo.results.InsertManyResult object at 0x101dea558>
# [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]
# 查詢,插入數據後咱們能夠利用find_one()或find()方法進行查詢,find_one()查詢獲得是單個結果,find()則返回多個結果。
  
result = collection.find_one({'name': 'Mike'})
print(type(result))
print(result)
# 在這裏咱們查詢name爲Mike的數據,它的返回結果是字典類型,運行結果:
# <class'dict'>
# {'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
# 能夠發現它多了一個_id屬性,這就是MongoDB在插入的過程當中自動添加的。
  
# 咱們也能夠直接根據ObjectId來查詢,這裏須要使用bson庫裏面的ObjectId。
  
from bson.objectid import ObjectId
  
result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})
print(result)
# 其查詢結果依然是字典類型,運行結果:
  
# {' ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
# 固然若是查詢_id':結果不存在則會返回None。
  
# 對於多條數據的查詢,咱們可使用find()方法,例如在這裏查找年齡爲20的數據,示例以下:
  
results = collection.find({'age': 20})
print(results)
for result in results:
    print(result)
# 運行結果:
  
# <pymongo.cursor.Cursor object at 0x1032d5128>
# {'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
# {'_id': ObjectId('593278c815c2602678bb2b8d'), 'id': '20170102', 'name': 'Kevin', 'age': 20, 'gender': 'male'}
# {'_id': ObjectId('593278d815c260269d7645a8'), 'id': '20170103', 'name': 'Harden', 'age': 20, 'gender': 'male'}
# 返回結果是Cursor類型,至關於一個生成器,咱們須要遍歷取到全部的結果,每個結果都是字典類型。
  
# 若是要查詢年齡大於20的數據,則寫法以下:
  
results = collection.find({'age': {'$gt': 20}})
# 在這裏查詢的條件鍵值已經不是單純的數字了,而是一個字典,其鍵名爲比較符號$gt,意思是大於,鍵值爲20,這樣即可以查詢出全部
# 年齡大於20的數據。
  
# 在這裏將比較符號概括以下表:
"""
符號含義示例
$lt小於{'age': {'$lt': 20}}
$gt大於{'age': {'$gt': 20}}
$lte小於等於{'age': {'$lte': 20}}
$gte大於等於{'age': {'$gte': 20}}
$ne不等於{'age': {'$ne': 20}}
$in在範圍內{'age': {'$in': [20, 23]}}
$nin不在範圍內{'age': {'$nin': [20, 23]}}
"""
# 另外還能夠進行正則匹配查詢,例如查詢名字以M開頭的學生數據,示例以下:
  
results = collection.find({'name': {'$regex': '^M.*'}})
# 在這裏使用了$regex來指定正則匹配,^M.*表明以M開頭的正則表達式,這樣就能夠查詢全部符合該正則的結果。
  
# 在這裏將一些功能符號再歸類以下:
"""
符號含義示例示例含義
$regex匹配正則{'name': {'$regex': '^M.*'}}name以M開頭
$exists屬性是否存在{'name': {'$exists': True}}name屬性存在
$type類型判斷{'age': {'$type': 'int'}}age的類型爲int
$mod數字模操做{'age': {'$mod': [5, 0]}}年齡模5餘0
$text文本查詢{'$text': {'$search': 'Mike'}}text類型的屬性中包含Mike字符串
$where高級條件查詢{'$where': 'obj.fans_count == obj.follows_count'}自身粉絲數等於關注數
"""
# 這些操做的更詳細用法在能夠在MongoDB官方文檔找到:
# https://docs.mongodb.com/manual/reference/operator/query/
  
# 計數
# 要統計查詢結果有多少條數據,能夠調用count()方法,如統計全部數據條數:
  
count = collection.find().count()
print(count)
# 或者統計符合某個條件的數據:
  
count = collection.find({'age': 20}).count()
print(count)
# 排序
# 能夠調用sort方法,傳入排序的字段及升降序標誌便可,示例以下:
  
results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])
# 運行結果:
  
# ['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike']
# 偏移,可能想只取某幾個元素,在這裏能夠利用skip()方法偏移幾個位置,好比偏移2,就忽略前2個元素,獲得第三個及之後的元素。
  
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
# 運行結果:
# ['Kevin', 'Mark', 'Mike']
# 另外還能夠用limit()方法指定要取的結果個數,示例以下:
  
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])
# 運行結果:
# ['Kevin', 'Mark']
# 若是不加limit()本來會返回三個結果,加了限制以後,會截取2個結果返回。
  
# 值得注意的是,在數據庫數量很是龐大的時候,如千萬、億級別,最好不要使用大的偏移量來查詢數據,極可能會致使內存溢出,
# 可使用相似find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}}) 這樣的方法來查詢,記錄好上次查詢的_id。
  
# 更新
# 對於數據更新可使用update()方法,指定更新的條件和更新後的數據便可,例如:
  
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result)
# 在這裏咱們將name爲Kevin的數據的年齡進行更新,首先指定查詢條件,而後將數據查詢出來,修改年齡,
# 以後調用update方法將原條件和修改後的數據傳入,便可完成數據的更新。
  
# 運行結果:
  
# {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
# 返回結果是字典形式,ok即表明執行成功,nModified表明影響的數據條數。
  
# 另外update()方法其實也是官方不推薦使用的方法,在這裏也分了update_one()方法和update_many()方法,用法更加嚴格,
# 第二個參數須要使用$類型操做符做爲字典的鍵名,咱們用示例感覺一下。
  
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)
# 在這裏調用了update_one方法,第二個參數不能再直接傳入修改後的字典,而是須要使用{'$set': student}這樣的形式,
# 其返回結果是UpdateResult類型,而後調用matched_count和modified_count屬性分別能夠得到匹配的數據條數和影響的數據條數。
  
# 運行結果:
#
# <pymongo.results.UpdateResult object at 0x10d17b678>
# 1 0
# 咱們再看一個例子:
  
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
# 在這裏咱們指定查詢條件爲年齡大於20,而後更新條件爲{'$inc': {'age': 1}},執行以後會講第一條符合條件的數據年齡加1。
  
# 運行結果:
#
# <pymongo.results.UpdateResult object at 0x10b8874c8>
# 1 1
# 能夠看到匹配條數爲1條,影響條數也爲1條。
  
# 若是調用update_many()方法,則會將全部符合條件的數據都更新,示例以下:
  
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
# 這時候匹配條數就再也不爲1條了,運行結果以下:
#
# <pymongo.results.UpdateResult object at 0x10c6384c8>
# 3 3
# 能夠看到這時全部匹配到的數據都會被更新。
  
# 刪除
# 刪除操做比較簡單,直接調用remove()方法指定刪除的條件便可,符合條件的全部數據均會被刪除,示例以下:
  
result = collection.remove({'name': 'Kevin'})
print(result)
# 運行結果:
#
# {'ok': 1, 'n': 1}
# 另外依然存在兩個新的推薦方法,delete_one()和delete_many()方法,示例以下:
  
result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)
# 運行結果:
  
# <pymongo.results.DeleteResult object at 0x10e6ba4c8>
# 1
# 4
# delete_one()即刪除第一條符合條件的數據,delete_many()即刪除全部符合條件的數據,返回結果是DeleteResult類型,
# 能夠調用deleted_count屬性獲取刪除的數據條數。
  
# 更多
# 另外PyMongo還提供了一些組合方法,如find_one_and_delete()、find_one_and_replace()、find_one_and_update(),
# 就是查找後刪除、替換、更新操做,用法與上述方法基本一致。
  
# 另外還能夠對索引進行操做,如create_index()、create_indexes()、drop_index()等。
  
# 詳細用法能夠參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/collection.html
  
# 另外還有對數據庫、集合自己以及其餘的一些操做,在這再也不一一講解,能夠參見
# 官方文檔:http://api.mongodb.com/python/current/api/pymongo/
複製代碼
相關文章
相關標籤/搜索