【Python網絡爬蟲整理記錄 D:06】——非關係型數據庫MongoDB安裝與pymongo庫的使用

MongoDB的安裝

windows下MongoDB的配置

進入MongoDB的安裝目錄下:

  1. 在data目錄下創建db文件夾
    複製db文件夾的路徑,打開cmd,進入MongoDB的bin目錄下:

    mongod --dbpath 'F:\ToolWarehouse\MongoDB\data\db'
    
  2. 在log目錄下創建mongodb.log文件

  3. 刪除原本的MongoDB服務

    sc delete MongoDB Server
    
  4. 創建新的服務,以管理員的身份運行cmd,進入MongoDB的bin目錄在:

    mongod --bind_ip 0.0.0.0 --logpath "F:\ToolWarehouse\MongoDB\log\mongodb.log" --logappend --dbpath "F:\ToolWarehouse\MongoDB\data\db" --port 27017 --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install
    
  5. 啓動新的服務
    在這裏插入圖片描述

Python中pymongo庫的使用

MongoDB的連接

# -*- coding: utf-8 -*-
# @Time    : 2020/2/21 16:24
# @Author  : Dchanong_
# @FileName: MongoDB的連接.py
# @Software: PyCharm
# @Cnblogs :https://blog.csdn.net/Dchanong_
import pymongo

'''
鏈接MongoDB數據庫
指定數據庫
指定集合
'''
# 連接MongoDB
client = pymongo.MongoClient(host='localhost', port=27017)
# 第二種連接方式
# client = pymongo.MongoClient('mongodb://localhost:27017')
# 指定數據庫
db = client.test
# 第二種指定數據庫的方法
# db = client['test']
# 指定集合,MongoDB的每個數據庫又包含許多集合(collection),類似於關係型數據庫中的表
collection = db.students
# 第二種指定集合的方法
# collection = db['students']

MongoDB的插入

# -*- coding: utf-8 -*-
# @Time    : 2020/2/21 16:24
# @Author  : Dchanong_
# @FileName: MongoDB的插入.py
# @Software: PyCharm
# @Cnblogs :https://blog.csdn.net/Dchanong_

import pymongo

'''
鏈接MongoDB數據庫
指定數據庫
指定集合
'''
# 連接MongoDB
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.students

'''
插入數據
'''
# 對於students這個集合,新建一個學生數據,這條數據以字典類型表示
student = {
    'id': '1',
    'name': 'ming',
    'age': '20'
}
# MongoDB中插入數據,直接調用collection的insert()方法即可插入數據
result = collection.insert(student)
print(result)  # 5e4f92c5edfe457b1a77502f
# 在MongoDB中,每條數據其實都有一個_id屬性來唯一標識,
# 如果沒有顯式指明該屬性,MongoDB會自動產生一個objectID的_id屬性
# insert()方法會在執行後返回_id值

# 多條插入,只需要一列表形式傳遞即可
student2 = {
    'id': '2',
    'name': 'tian',
    'age': '21'
}
student3 = {
    'id': '3',
    'name': 'ding',
    'age': '22'
}
result = collection.insert([student2, student3])
print(result)  # [ObjectId('5e4f93a7a9ca3a0f5dd69ee2'), ObjectId('5e4f93a7a9ca3a0f5dd69ee3')]
# 官方推薦使用insert_one()和isnert_many()方法來分別插入單條記錄和多條記錄
student4 = {
    'id': '4',
    'name': 'tani',
    'age': '21'
}
result = collection.insert_one(student4)
print(result)  # <pymongo.results.InsertOneResult object at 0x00000271DF4F6908>
print(result.inserted_id)  # 5e4f9472bf45b85489b5ca19
# 與insert()方法不同的是,這裏返回的是InsertOneResult對象,可以調用此對象的inserted_id屬性獲取id值
# insert_many()同理

MongoDB的查詢

# -*- coding: utf-8 -*-
# @Time    : 2020/2/21 16:32
# @Author  : Dchanong_
# @FileName: MongoDB的查詢.py
# @Software: PyCharm
# @Cnblogs :https://blog.csdn.net/Dchanong_
import pymongo

'''
鏈接MongoDB數據庫
指定數據庫
指定集合
'''
# 連接MongoDB
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.students

'''
查詢數據、計數、排序、偏移
'''
result = collection.find_one({'id': '4'})
print(result)  # {'_id': ObjectId('5e4f9472bf45b85489b5ca19'), 'id': '4', 'name': 'tani', 'age': '21'}
print((type(result)))  # <class 'dict'>

# 對於多條數據的查詢,可以使用find()方法,數據不存在則返回None
results = collection.find({'age': '20'})
print(results)  # <pymongo.cursor.Cursor object at 0x0000013B5AD44BE0>
print(type(results))  # <class 'pymongo.cursor.Cursor'>
for result in results:
    print(result)
# {'_id': ObjectId('5e4f92419fc49f329a7be721'), 'id': '1', 'name': 'ming', 'age': '20'}
# {'_id': ObjectId('5e4f92bedcdc4f4eef54813f'), 'id': '1', 'name': 'ming', 'age': '20'}
# {'_id': ObjectId('5e4f92c5edfe457b1a77502f'), 'id': '1', 'name': 'ming', 'age': '20'}
# {'_id': ObjectId('5e4f93a7a9ca3a0f5dd69ee1'), 'id': '1', 'name': 'ming', 'age': '20'}
# {'_id': ObjectId('5e4f9472bf45b85489b5ca16'), 'id': '1', 'name': 'ming', 'age': '20'}
print('*' * 40)
# 要查詢age值大於20的數據
results = collection.find({'age': {'$gt': '20'}})
for result in results:
    print(result)
# {'_id': ObjectId('5e4f93a7a9ca3a0f5dd69ee2'), 'id': '2', 'name': 'tian', 'age': '21'}
# {'_id': ObjectId('5e4f93a7a9ca3a0f5dd69ee3'), 'id': '3', 'name': 'ding', 'age': '22'}
# {'_id': ObjectId('5e4f9472bf45b85489b5ca17'), 'id': '2', 'name': 'tian', 'age': '21'}
# {'_id': ObjectId('5e4f9472bf45b85489b5ca18'), 'id': '3', 'name': 'ding', 'age': '22'}
# {'_id': ObjectId('5e4f9472bf45b85489b5ca19'), 'id': '4', 'name': 'tani', 'age': '21'}

# 計數
count = collection.find().count()
print(count)  # 10

# 排序
# 直接調用sort()方法,並在其中傳入排序的字段以及升降序標誌即可
results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])
# ['ding', 'ding', 'ming', 'ming', 'ming', 'ming', 'ming', 'tani', 'tian', 'tian']

# 偏移
# 只取某幾個數據,可以利用skip()方法偏移幾個位置
# 比如偏移2,就忽略前面兩個元素,得到第三個及以後的元素
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
# ['ming', 'ming', 'ming', 'ming', 'ming', 'tani', 'tian', 'tian']
# 還可以使用limit()方法指定要取的結果個數
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])
# ['ming', 'ming']

MongoDB的更新

# -*- coding: utf-8 -*-
# @Time    : 2020/2/21 16:51
# @Author  : Dchanong_
# @FileName: MongoDB的更新.py
# @Software: PyCharm
# @Cnblogs :https://blog.csdn.net/Dchanong_

import pymongo

'''
鏈接MongoDB數據庫
指定數據庫
指定集合
'''
# 連接MongoDB
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.students

'''
數據的更新
'''
condition = {'name': 'tani'}
student = collection.find_one(condition)
student['name'] = 'tian'
result = collection.update(condition, student)
print(result)  # {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}

# 官方推薦使用update_one()方法以及update_many()方法
condition = {'id': '4'}
student = collection.find_one(condition)
student['id'] = '5'
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)
# <pymongo.results.UpdateResult object at 0x000001D96B85AA88>
# 1 1

condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 10}})
print(result)
print(result.matched_count, result.modified_count)

MongoDB的刪除

# -*- coding: utf-8 -*-
# @Time    : 2020/2/21 17:19
# @Author  : Dchanong_
# @FileName: MongoDB的刪除.py
# @Software: PyCharm
# @Cnblogs :https://blog.csdn.net/Dchanong_

import pymongo

'''
鏈接MongoDB數據庫
指定數據庫
指定集合
'''
# 連接MongoDB
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.students

'''
數據的刪除
'''

result = collection.remove({'name': 'ding'})
print(result)  # {'n': 2, 'ok': 1.0}

# 官方推薦方法 delete_one()    delete_many()方法
result = collection.delete_many({'name': 'tian'})
print(result)  # <pymongo.results.DeleteResult object at 0x000001A7CE3FC9C8>
print(result.deleted_count)  # 3
result = collection.delete_one({'id': '1'})
print(result)  # <pymongo.results.DeleteResult object at 0x000001A7CE3FCA08>
print(result.deleted_count)  # 1

'''
pymongeo還體統一些組合方法,如
find_one_delete()   查找後刪除
find_one_replace()  查找後替換
find_one_and_update()   查找後更新
具體操作相差不多
'''

MongoDB中的比較符號

符號 含義 示例
$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]}}

MongoDB中的功能符號

符號 含義 示例 示例含義
$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’} 自身粉絲數等於關注數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章