爬虫文件存储-2:MongoDB
1.连接MongoDB
连接 MongoDB 我们需要使用 PyMongo 库里面的 MongoClient,一般来说传入 MongoDB 的 IP 及端口即可,第一个参数为地址 host,第二个参数为端口 port,端口如果不传默认是 27017。
- 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 的每个数据库又包含了许多集合 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.插入数据
在 MongoDB 中,每条数据其实都有一个 _id 属性来唯一标识,如果没有显式指明 _id,MongoDB 会自动产生一个 ObjectId 类型的 _id 属性。insert() 方法会在执行后返回的 _id 值。也可以在插入的时候指定_id的值。
也可以同时插入多条数据,只需要以列表形式传递即可,返回的结果是对应的 _id 的集合。
- 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': '',
- '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': '',
- 'name': 'Jordan',
- 'age': 20,
- 'gender': 'male'
- }
- student2 = {
- 'id': '',
- '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.查询数据
可以利用 find_one() 或 find() 方法进行查询,find_one() 查询得到是单个结果,find() 则返回一个生成器对象。
- 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 |
小于 |
|
$gt |
大于 |
|
$lte |
小于等于 |
|
$gte |
大于等于 |
|
$ne |
不等于 |
|
$in |
在范围内 |
|
$nin |
不在范围内 |
|
- # 还可以进行正则匹配查询,例如查询名字以 M 开头的学生数据
- results = collection.find({'name': {'$regex': '^M.*'}}) # 使用了 $regex 来指定正则匹配,^M.* 代表以 M 开头的正则表达式s
符号 |
含义 |
示例 |
示例含义 |
$regex |
匹配正则 |
|
name 以 M开头 |
$exists |
属性是否存在 |
|
name 属性存在 |
$type |
类型判断 |
|
age 的类型为 int |
$mod |
数字模操作 |
|
年龄模 5 余 0 |
$text |
文本查询 |
|
text 类型的属性中包含 Mike 字符串 |
$where |
高级条件查询 |
|
自身粉丝数等于关注数 |
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/
爬虫文件存储-2:MongoDB的更多相关文章
- 【网络爬虫入门05】分布式文件存储数据库MongoDB的基本操作与爬虫应用
[网络爬虫入门05]分布式文件存储数据库MongoDB的基本操作与爬虫应用 广东职业技术学院 欧浩源 1.引言 网络爬虫往往需要将大量的数据存储到数据库中,常用的有MySQL.MongoDB和Red ...
- 04 爬虫数据存储之Mongodb
MongoDB 认识MongoDB MongoDB是一个基于分布式文件存储的数据库.由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案.MongoDB是一个介于关系数据库和非关系数据 ...
- 爬虫文件存储:txt文档,json文件,csv文件
5.1 文件存储 文件存储形式可以是多种多样的,比如可以保存成 TXT 纯文本形式,也可以保存为 Json 格式.CSV 格式等,本节我们来了解下文本文件的存储方式. 5.1.1 TXT文本存储 将数 ...
- 分布式文件存储数据库 MongoDB
MongoDB 简介 Mongo 并非芒果(Mango)的意思,而是源于 Humongous(巨大的:庞大的)一词. MongoDB 是一个基于分布式文件存储的 NoSQL 数据库.由 C++ 语言编 ...
- 爬虫—文件存储—CSV存储
一,简介 CSV,全称Comma—Separated Values,可以称为逗号分隔或者字符分隔值,其文件以纯文本形式存储表格数据.该文件是一个字符序列,可以有任意的数目记录组成,记录间已某种换行符分 ...
- 爬虫文件存储-3:Redis
前提条件: 安装并运行redis服务端程序,安装RedisPy库 说明:Redis 是 StrictRedis 的子类,它的主要功能是用于向后兼容旧版本库里的几个方法,官方推荐使用 StrictRed ...
- 爬虫文件存储-1:mysql
1.连接并创建数据库 import pymysql db = pymysql.connect(host='localhost', user='root', password='root', port= ...
- Python爬虫框架Scrapy实例(三)数据存储到MongoDB
Python爬虫框架Scrapy实例(三)数据存储到MongoDB任务目标:爬取豆瓣电影top250,将数据存储到MongoDB中. items.py文件复制代码# -*- coding: utf-8 ...
- MongoDb gridfs-ngnix文件存储方案
在各类系统应用服务端开发中,我们经常会遇到文件存储的问题. 常见的磁盘文件系统,DBMS传统文件流存储.今天我们看一下基于NoSQL数据库MongoDb的存储方案.笔者环境 以CentOS ...
随机推荐
- string转date
/*util-->sql*/ java.util.Date utdt; java.sql.Date sqldt =null; SimpleDateFormat simFormat = new S ...
- RDA EQ&频响曲线
相关数据: FAC->Audio->EQ Setting EQ Band - Gain Frequency Q Factor 1.5 FAC->Audio->PEQ // En ...
- MSP430:中断简介
(5).中断应用程序举例(外部中断): void interrupt_initial() { P1DIR&=~BIT7; //P1.7为输入 P1IE|=0x80; //P ...
- ubuntu下设置共享目录
在使用VirtualBox和相关的客户机系统比如XPMac等需要用到一些相关功能共享剪贴板等等这时候需要安装VirtualBox中的一个工具叫做Guest Additions中文叫法不一增强工具包功能 ...
- Oracle group by分组拼接字符串
select wm_concat(id),depon from test_1 group by depon
- TypeScript `infer` 关键字
考察如下类型: type PromiseType<T> = (args: any[]) => Promise<T>; 那么对于符合上面类型的一个方法,如何得知其 Prom ...
- excel另存为csv
# -*- coding: utf-8 -*- """ Created on Tue Jul 11 21:25:57 2017 import pandas as pd i ...
- JS高级——Function原型链
基本概念 1.函数可以通过Function new出来,那么Function可以被称作构造函数,被new出来的函数可以被称为一个对象 2.Function既然是构造函数,那么肯定也有原型,它的原型是一 ...
- html——a标签中target属性
有 4 个保留的目标名称用作特殊的文档重定向操作: _blank 浏览器总在一个新打开.未命名的窗口中载入目标文档. _self 这个目标的值对所有没有指定目标的 <a> 标签是默认目标, ...
- 控制台——EventLog实现事件日志操作
我们应该如何通过写代码的方式向其中添加“日志”呢? 在操作之前,先明确几个概念: 1:事件日志名(logName):“事件查看器”中的每一项,如“应用程序”.“Internet Explorer”.“ ...