爬蟲文件存儲-2:MongoDB

1.鏈接MongoDBhtml

鏈接 MongoDB 咱們須要使用 PyMongo 庫裏面的 MongoClient,通常來講傳入 MongoDB 的 IP 及端口便可,第一個參數爲地址 host,第二個參數爲端口 port,端口若是不傳默認是 27017。python

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')

2.指定數據庫正則表達式

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']

3.指定集合mongodb

MongoDB 的每一個數據庫又包含了許多集合 Collection,也就相似與關係型數據庫中的表數據庫

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']
collection = db.students
# collection = db['students']

4.插入數據api

在 MongoDB 中,每條數據其實都有一個 _id 屬性來惟一標識,若是沒有顯式指明 _id,MongoDB 會自動產生一個 ObjectId 類型的 _id 屬性。insert() 方法會在執行後返回的 _id 值。也能夠在插入的時候指定_id的值。spa

也能夠同時插入多條數據,只須要以列表形式傳遞便可,返回的結果是對應的 _id 的集合。3d

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']
collection = db.students
# collection = db['students']

# 插入單條數據
student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

result = collection.insert_one(student)
print(result)
print(result.inserted_id) # 返回的是InsertOneResult 對象,咱們能夠調用其 inserted_id 屬性獲取 _id
"""
運行結果:
<pymongo.results.InsertOneResult object at 0x10d68b558>
5932ab0f15c2606f0c1cf6c5
"""

# 插入多條數據
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')]

"""

5.查詢數據code

能夠利用 find_one() 或 find() 方法進行查詢,find_one() 查詢獲得是單個結果,find() 則返回一個生成器對象。htm

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']
collection = db.students
# collection = db['students']

result = collection.find_one({'name': 'Mike'})
print(type(result)) # 查詢 name 爲 Mike 的數據,它的返回結果是字典類型
print(result) # 多了一個 _id 屬性,這就是 MongoDB 在插入的過程當中自動添加的
"""
<class 'dict'>
{'_id': ObjectId('5c502697e0b72c0d90eeee22'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
"""

# 也能夠直接根據 ObjectId 來查詢,這裏須要使用 bson 庫裏面的 ObjectId
"""
from bson.objectid import ObjectId

result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})
print(result)

"""

# 多條數據的查詢,使用 find() 方法
results = collection.find({'age': 20})
print(results)
for result in results:
    print(result) # 返回結果是 Cursor 類型,至關於一個生成器,咱們須要遍歷取到全部的結果,每個結果都是字典類型

# 要查詢年齡大於 20 的數據
results = collection.find({'age': {'$gt': 20}}) # 查詢的條件鍵值是一個字典,其鍵名爲比較符號 $gt,意思是大於,鍵值爲 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 開頭的正則表達式s

符號

含義

示例

示例含義

$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'}

自身粉絲數等於關注數

 

 6.統計/計數

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']
collection = db.students

count = collection.find().count() # 統計全部數據條數
print(count)

count = collection.find({'age': 20}).count() # 統計符合某個條件的數據
print(count)

7.排序

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']
collection = db.students

results = collection.find().sort('name', pymongo.ASCENDING) # pymongo.ASCENDING 指定升序,降序排列能夠傳入 pymongo.DESCENDING
print([result['name'] for result in results])

8.偏移

注意:在數據庫數量很是龐大的時候,如千萬、億級別,最好不要使用大的偏移量來查詢數據,極可能會致使內存溢出,使用步驟5進行查詢

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']
collection = db.students

# 在某些狀況下咱們可能想只取某幾個元素,在這裏能夠利用skip() 方法偏移幾個位置,好比偏移 2,就忽略前 2 個元素,獲得第三個及之後的元素
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])

# 還能夠用 limit() 方法指定要取的結果個數
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])

9.更新

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']
collection = db.students

# update_one和update_many,第一個參數是條件,第二個參數須要使用 $ 類型操做符做爲字典的鍵名

condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
# 返回結果是 UpdateResult 類型,調用 matched_count 和 modified_count 屬性分別能夠得到匹配的數據條數和影響的數據條數
print(result)
print(result.matched_count, result.modified_count)

# 指定查詢條件爲年齡大於 20,而後更新條件爲 {'$inc': {'age': 1}},也就是年齡加 1,執行以後會將第一條符合條件的數據年齡加 1
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

# 調用 update_many() 方法,則會將全部符合條件的數據都更新
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

10.刪除

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
db = client.test
# db = client['test']
collection = db.students

# delete_one() 即刪除第一條符合條件的數據,delete_many() 即刪除全部符合條件的數據
# 返回結果是 DeleteResult 類型,能夠調用 deleted_count 屬性獲取刪除的數據條數

result = collection.delete_one({'name': 'Mike'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)

11.組合方法

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/

相關文章
相關標籤/搜索