爬虫之非关系型数据库MongoDB存储
- 以下是MongoDB在python中整个代码常用功能实现:关于连接MongoDB、指定数据库、指定集合、插入数据、查询数据、计数、排序、偏移、更新、删除这10个功能代码块的实现方法;
代码获取地址:https://github.com/Shirmay1/Python3Spider/blob/master/MongoDB/basic_use.py
# python3中存储数据到MongoDB
import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient(host='localhost',port=27017)
db = client.test
collection = db.students
student1 = {
'id':'20170101',
'name':'ShirMay1',
'age':23,
'gender':'felmale'
}
student2 = {
'id':'20170102',
'name':'Hardon',
'age':20,
'gender':'male'
}
student3 = {
'id':'20170103',
'name':'Jordan',
'age':20,
'gender':'male'
}
student4 = {
'id':'20170104',
'name':'Mike',
'age':21,
'gender':'male'
}
student5 = {
'id':'20170105',
'name':'Kevin',
'age':20,
'gender':'male'
}
#insert_one()插入单条数据
insert_result = collection.insert_one(student1)
print(insert_result)
print(insert_result.inserted_id)
#insert_many()插入多条数据
insert_result = collection.insert_many([student2,student3,student4,student5])
print(insert_result)
print(insert_result.inserted_ids)
#find_one()方法查询name为Mike的数据
query_result = collection.find_one({'name':'Mike'})
print(type(query_result))
print(query_result)
#find_one()方法根据ObjectId来查询
query_result_id = collection.find_one({'_id': ObjectId('5c9b36b5fe0bea232819c8ea')})
print(query_result_id)
#find()方法查询年龄为20的数据
query_result_ages = collection.find({'age':20})
print(query_result_ages)
for result in query_result_ages:
print(result)
#find()方法查询年龄大于20的数据
query_ages20 = collection.find({'age':{'$gt':20}})
print(query_ages20)
for result in query_ages20:
print(result)
#count_documents()方法计数
count = collection.count_documents({})
print(count)
count1 = collection.count_documents({'age':20})
print(count1)
#sort()方法排序
sort_result = collection.find().sort('name',pymongo.ASCENDING)
print([result['name'] for result in sort_result])
#偏移
skip_result = collection.find().sort('name',pymongo.ASCENDING).skip(2)
print([result['name'] for result in skip_result])
#偏移取1个结果
skip_result1 = collection.find().sort('name',pymongo.ASCENDING).skip(2).limit(1)
print([result['name'] for result in skip_result1])
#update_one()更新name为Kevin的数据的年龄
condition = {'name':'Kevin'}
student = collection.find_one(condition)
student['age'] = 24
result = collection.update_one(condition,{'$set':student})
print(result)
print(result.matched_count,result.modified_count)
#update_one()更新年龄大于20的年龄加1
condition = {'age':{'$gt':20}}
result = collection.update_one(condition,{'$inc':{'age':1}})
print(result)
print(result.matched_count,result.modified_count)
#update_many()更新年龄大于20的年龄加1
condition = {'age':{'$gt':20}}
result = collection.update_many(condition,{'$inc':{'age':1}})
print(result)
print(result.matched_count,result.modified_count)
#删除
result = collection.delete_one({'name':'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age':{'$lt':25}})
print(result.deleted_count)
1、准备工作
- 安装好MongoDB并启动了服务
- 安装好Python的pymongo库(命令窗口执行pip install pymongo)
2、连接MongoDB、指定数据库、指定集合、插入数据、查询数据、计数、排序、偏移、更新、删除
- (1)创建MongoDB连接对象client:
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
- (2)指定数据库,调用client的属性test,即可返回test数据库:
db = client.test
- (3)指定集合,每个数据库又包含许多集合(它们类似于关系型数据库中的表),如集合students,如下命令便申明了Collection对象:
collection = db.students
- (4)插入数据,对于students这个集合,新建一条学生数据,这条数据以字典形式表示 ,这里指定了学生的学号、姓名、年龄和性别。
__接下来直接调用collection的insert_one()和insert_many()方法分别插入单条或者多条数据。
__在MongoDB中每条数据其实都有一个_id属性来唯一标识,如果没有显示指明该属性,MongoDB会自动产生一个ObjectId类型的_id属性。
student1 = {
'id':'20170101',
'name':'ShirMay1',
'age':23,
'gender':'felmale'
}
student2 = {
'id':'20170102',
'name':'Hardon',
'age':20,
'gender':'male'
}
student3 = {
'id':'20170103',
'name':'Jordan',
'age':20,
'gender':'male'
}
student4 = {
'id':'20170104',
'name':'Mike',
'age':21,
'gender':'male'
}
student5 = {
'id':'20170105',
'name':'Kevin',
'age':20,
'gender':'male'
}
#insert_one()插入单条数据
insert_result = collection.insert_one(student1)
print(insert_result)
print(insert_result.inserted_id)
#运行结果:
<pymongo.results.InsertOneResult object at 0x0000000002860508>
5c9b36b5fe0bea232819c8e7
#insert_many()插入多条数据
insert_result = collection.insert_many([student2,student3,student4,student5])
print(insert_result)
print(insert_result.inserted_ids)
#运行结果
<pymongo.results.InsertManyResult object at 0x0000000002A6F7C8>
[ObjectId('5c9b36b5fe0bea232819c8e8'), ObjectId('5c9b36b5fe0bea232819c8e9'), ObjectId('5c9b36b5fe0bea232819c8ea'), ObjectId('5c9b36b5fe0bea232819c8eb')]
- (5)查询,用find_one()和find()查询,find_one()查询得到的是单个结果字典类型,find()则返回一个生成器对象。
#find_one()方法查询name为Mike的数据
query_result = collection.find_one({'name':'Mike'})
print(type(query_result))
print(query_result)
#运行结果如下:
<class 'dict'>
{'_id': ObjectId('5c9b36b5fe0bea232819c8ea'), 'id': '20170104', 'name': 'Mike', 'age': 21, 'gender': 'male'}
#find_one()方法根据ObjectId来查询
from bson.objectid import ObjectId
query_result_id = collection.find_one({'_id': ObjectId('5c9b36b5fe0bea232819c8ea')})
print(query_result_id)
#运行结果如下:
{'_id': ObjectId('5c9b36b5fe0bea232819c8ea'), 'id': '20170104', 'name': 'Mike', 'age': 21, 'gender': 'male'}
#find()方法查询年龄为20的数据
query_result_ages = collection.find({'age':20})
print(query_result_ages)
for result in query_result_ages:
print(result)
#运行结果如下:
<pymongo.cursor.Cursor object at 0x0000000002C1D630>
{'_id': ObjectId('5c9b36b5fe0bea232819c8e8'), 'id': '20170102', 'name': 'Hardon', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('5c9b36b5fe0bea232819c8e9'), 'id': '20170103', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('5c9b36b5fe0bea232819c8eb'), 'id': '20170105', 'name': 'Kevin', 'age': 20, 'gender': 'male'}
#find()方法查询年龄大于20的数据
query_ages20 = collection.find({'age':{'$gt':20}})
print(query_ages20)
for result in query_ages20:
print(result)
#运行结果如下:
<pymongo.cursor.Cursor object at 0x0000000002C21438>
{'_id': ObjectId('5c9b36b5fe0bea232819c8e7'), 'id': '20170101', 'name': 'ShirMay1', 'age': 23, 'gender': 'felmale'}
{'_id': ObjectId('5c9b36b5fe0bea232819c8ea'), 'id': '20170104', 'name': 'Mike', 'age': 21, 'gender': 'male'}
比较符号表:
符号 | 含义 | 示例 |
---|---|---|
$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]}} |
功能符号表:
符号 | 含义 | 示例 | 示例含义 |
---|---|---|---|
$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 | 文本查询 | {‘ search’:‘Mike’} | text类型的属性中包含Mike字符串 |
$where | 高级条件查询 | {‘$where’:‘obj.fans_count==obj.follows_count’} | 自身粉丝数等于关注数 |
- (6)计数,调用count_documents()方法
#count_documents()方法计数
count = collection.count_documents({})
print(count)
count1 = collection.count_documents({'age':20})
print(count1)
#运行结果如下
5
3
- (7)排序,调用sort()方法,pymongo.ASCENDING升序(先大写字母后小写字母排序),pymongo.DESCENDING降序;
#sort()方法排序
sort_result = collection.find().sort('name',pymongo.ASCENDING)
print([result['name'] for result in sort_result])
#运行结果如下
['Hardon', 'Jordan', 'Kevin', 'Mike', 'ShirMay1']
- (8)偏移,调用skip()方法,比如偏移2,就忽略前两个元素,得到第三个及以后的元素;另外limit()方法可以指定取几个结果
#偏移
skip_result = collection.find().sort('name',pymongo.ASCENDING).skip(2)
print([result['name'] for result in skip_result])
#运行结果
['Kevin', 'Mike', 'ShirMay1']
#偏移取1个结果
skip_result1 = collection.find().sort('name',pymongo.ASCENDING).skip(2).limit(1)
print([result['name'] for result in skip_result1])
#运行结果
['Kevin']
- (9)更新,update_one()和update_many()方法,指定更新的条件和更新后的数据即可,
__更新name为Kevin的数据的年龄:首先指定查询条件,然后将数据查询出来,修改年龄后调用update_one()方法将原条件和修改后的数据传入;
__然后调用matched_count,modified_count属性,可以获得匹配的数据条数和影响的数据条数
#update_one()更新name为Kevin的数据的年龄
condition = {'name':'Kevin'}
student = collection.find_one(condition)
student['age'] = 24
result = collection.update_one(condition,{'$set':student})
print(result)
print(result.matched_count,result.modified_count)
#运行结果
<pymongo.results.UpdateResult object at 0x0000000002A70B08>
1 1
#update_one()更新年龄大于20的年龄加1
condition = {'age':{'$gt':20}}
result = collection.update_one(condition,{'$inc':{'age':1}})
print(result)
print(result.matched_count,result.modified_count)
#运行结果
<pymongo.results.UpdateResult object at 0x0000000002A707C8>
1 1
#update_many()更新年龄大于20的年龄加1
condition = {'age':{'$gt':20}}
result = collection.update_many(condition,{'$inc':{'age':1}})
print(result)
print(result.matched_count,result.modified_count)
#运行结果
<pymongo.results.UpdateResult object at 0x00000000029230C8>
3 3
(10)删除,delete_one()和delete_many()
__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 0x0000000002A774C8>
1
3