python 爬虫的数据存储问题 本文结合MongoDb

学习自《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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值