学习自《python3网络爬虫开发实战》, 整理以备日后回顾
自己平时习惯用 MongoDb ,所以在这也是存数据到 MongoDb
开始连接之前,要先启动服务,方法见 —> MongoDb 服务启动
pymongo 的话是第三方库,需要安装
pycharm 第三方库安装流程 File —> settings —> Project —> Interpreter —> + —> install
- 指定集合
# 导入包
import pymongo
# 创建连接
client = pymongo.MongoClient(host='localhost',port=27017)
# client = pymongo.MOngoClient('mongodb://localhost:27017/') 第二种方法
# 指定数据库
db = client.test
# 指定集合
collection = db.students
- 查询数据
# 查询单一数据
result_one = collection.find_one({'name': 'hfox'})
print(result_one)
# 查询多个数据
results = collection.find({'name': 'hfox'})
for result in results:
print(result)
- 插入数据
# 插入单一数据
student = {
'name': 'hfox',
'age': '68',
'gender': 'female',
'work': 'happy',
}
collection.insert_one(student)
# 查询多个数据
student_first = {
'name': 'hhfox',
'age': '46',
}
student_second = {
'name': 'hhfox',
'work': 'happy',
}
collection.insert_many([student_first,student_second])
- 删除数据
# 删除单一数据
result = collection.delete_one({'name': 'hfox'})
# 删除多个数据
result = collection.delete_many({'age': {'$lt':9 25}})
- 更新数据
condition = {'name': 'hfox'}
student = collection.find_one(condition)
student['age'] = 88
result = collection.update_one(condition, {'$set': student})
print(result)
- 一些其他操作
# 计数
count = collection.count_documents({'name': 'hhfox'})
print(count)
# sort()排序,默认升序, skip(2)偏移,是从第2个数据开始, limit(2)限制数量,是取两个数据
# 升序 pymongo.ASCENDING
# 降序 pymongo.DESCENDING
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
for result in results:
print(result)