1.连接MongoDB

连接 MongoDB 我们需要使用 PyMongo 库里面的 MongoClient,一般来说传入 MongoDB 的 IP 及端口即可,第一个参数为地址 host,第二个参数为端口 port,端口如果不传默认是 27017。

  1. import pymongo
  2. client = pymongo.MongoClient(host='localhost', port=27017)
  3. # client = MongoClient('mongodb://localhost:27017/')

2.指定数据库

  1. import pymongo
  2. client = pymongo.MongoClient(host='localhost', port=27017)
  3. # client = MongoClient('mongodb://localhost:27017/')
  4. db = client.test
  5. # db = client['test']

3.指定集合

MongoDB 的每个数据库又包含了许多集合 Collection,也就类似与关系型数据库中的表

  1. import pymongo
  2. client = pymongo.MongoClient(host='localhost', port=27017)
  3. # client = MongoClient('mongodb://localhost:27017/')
  4. db = client.test
  5. # db = client['test']
  6. collection = db.students
  7. # collection = db['students']

4.插入数据

在 MongoDB 中,每条数据其实都有一个 _id 属性来唯一标识,如果没有显式指明 _id,MongoDB 会自动产生一个 ObjectId 类型的 _id 属性。insert() 方法会在执行后返回的 _id 值。也可以在插入的时候指定_id的值。

也可以同时插入多条数据,只需要以列表形式传递即可,返回的结果是对应的 _id 的集合。

  1. import pymongo
  2. client = pymongo.MongoClient(host='localhost', port=27017)
  3. # client = MongoClient('mongodb://localhost:27017/')
  4. db = client.test
  5. # db = client['test']
  6. collection = db.students
  7. # collection = db['students']
  8.  
  9. # 插入单条数据
  10. student = {
  11. 'id': '',
  12. 'name': 'Jordan',
  13. 'age': 20,
  14. 'gender': 'male'
  15. }
  16.  
  17. result = collection.insert_one(student)
  18. print(result)
  19. print(result.inserted_id) # 返回的是InsertOneResult 对象,我们可以调用其 inserted_id 属性获取 _id
  20. """
  21. 运行结果:
  22. <pymongo.results.InsertOneResult object at 0x10d68b558>
  23. 5932ab0f15c2606f0c1cf6c5
  24. """
  25.  
  26. # 插入多条数据
  27. student1 = {
  28. 'id': '',
  29. 'name': 'Jordan',
  30. 'age': 20,
  31. 'gender': 'male'
  32. }
  33.  
  34. student2 = {
  35. 'id': '',
  36. 'name': 'Mike',
  37. 'age': 21,
  38. 'gender': 'male'
  39. }
  40.  
  41. result = collection.insert_many([student1, student2])
  42. print(result)
  43. print(result.inserted_ids) # insert_many() 方法返回的类型是 InsertManyResult,调用inserted_ids 属性可以获取插入数据的 _id 列表
  44. """
  45. 运行结果:
  46. <pymongo.results.InsertManyResult object at 0x101dea558>
  47. [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]
  48.  
  49. """

5.查询数据

可以利用 find_one() 或 find() 方法进行查询,find_one() 查询得到是单个结果,find() 则返回一个生成器对象。

  1. import pymongo
  2. client = pymongo.MongoClient(host='localhost', port=27017)
  3. # client = MongoClient('mongodb://localhost:27017/')
  4. db = client.test
  5. # db = client['test']
  6. collection = db.students
  7. # collection = db['students']
  8.  
  9. result = collection.find_one({'name': 'Mike'})
  10. print(type(result)) # 查询 name 为 Mike 的数据,它的返回结果是字典类型
  11. print(result) # 多了一个 _id 属性,这就是 MongoDB 在插入的过程中自动添加的
  12. """
  13. <class 'dict'>
  14. {'_id': ObjectId('5c502697e0b72c0d90eeee22'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
  15. """
  16.  
  17. # 也可以直接根据 ObjectId 来查询,这里需要使用 bson 库里面的 ObjectId
  18. """
  19. from bson.objectid import ObjectId
  20.  
  21. result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})
  22. print(result)
  23.  
  24. """
  25.  
  26. # 多条数据的查询,使用 find() 方法
  27. results = collection.find({'age': 20})
  28. print(results)
  29. for result in results:
  30. print(result) # 返回结果是 Cursor 类型,相当于一个生成器,我们需要遍历取到所有的结果,每一个结果都是字典类型
  31.  
  32. # 要查询年龄大于 20 的数据
  33. results = collection.find({'age': {'$gt': 20}}) # 查询的条件键值是一个字典,其键名为比较符号 $gt,意思是大于,键值为 20

符号

含义

示例

$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]}}

  1. # 还可以进行正则匹配查询,例如查询名字以 M 开头的学生数据
  2. results = collection.find({'name': {'$regex': '^M.*'}}) # 使用了 $regex 来指定正则匹配,^M.* 代表以 M 开头的正则表达式s

符号

含义

示例

示例含义

$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'}

自身粉丝数等于关注数

  1.  

6.统计/计数

  1. import pymongo
  2.  
  3. client = pymongo.MongoClient(host='localhost', port=27017)
  4. # client = MongoClient('mongodb://localhost:27017/')
  5. db = client.test
  6. # db = client['test']
  7. collection = db.students
  8.  
  9. count = collection.find().count() # 统计所有数据条数
  10. print(count)
  11.  
  12. count = collection.find({'age': 20}).count() # 统计符合某个条件的数据
  13. print(count)

7.排序

  1. import pymongo
  2.  
  3. client = pymongo.MongoClient(host='localhost', port=27017)
  4. # client = MongoClient('mongodb://localhost:27017/')
  5. db = client.test
  6. # db = client['test']
  7. collection = db.students
  8.  
  9. results = collection.find().sort('name', pymongo.ASCENDING) # pymongo.ASCENDING 指定升序,降序排列可以传入 pymongo.DESCENDING
  10. print([result['name'] for result in results])

8.偏移

注意:在数据库数量非常庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,很可能会导致内存溢出,使用步骤5进行查询

  1. import pymongo
  2.  
  3. client = pymongo.MongoClient(host='localhost', port=27017)
  4. # client = MongoClient('mongodb://localhost:27017/')
  5. db = client.test
  6. # db = client['test']
  7. collection = db.students
  8.  
  9. # 在某些情况下我们可能想只取某几个元素,在这里可以利用skip() 方法偏移几个位置,比如偏移 2,就忽略前 2 个元素,得到第三个及以后的元素
  10. results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
  11. print([result['name'] for result in results])
  12.  
  13. # 还可以用 limit() 方法指定要取的结果个数
  14. results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
  15. print([result['name'] for result in results])

9.更新

  1. import pymongo
  2.  
  3. client = pymongo.MongoClient(host='localhost', port=27017)
  4. # client = MongoClient('mongodb://localhost:27017/')
  5. db = client.test
  6. # db = client['test']
  7. collection = db.students
  8.  
  9. # update_one和update_many,第一个参数是条件,第二个参数需要使用 $ 类型操作符作为字典的键名
  10.  
  11. condition = {'name': 'Mike'}
  12. student = collection.find_one(condition)
  13. student['age'] = 26
  14. result = collection.update_one(condition, {'$set': student})
  15. # 返回结果是 UpdateResult 类型,调用 matched_count 和 modified_count 属性分别可以获得匹配的数据条数和影响的数据条数
  16. print(result)
  17. print(result.matched_count, result.modified_count)
  18.  
  19. # 指定查询条件为年龄大于 20,然后更新条件为 {'$inc': {'age': 1}},也就是年龄加 1,执行之后会将第一条符合条件的数据年龄加 1
  20. condition = {'age': {'$gt': 20}}
  21. result = collection.update_one(condition, {'$inc': {'age': 1}})
  22. print(result)
  23. print(result.matched_count, result.modified_count)
  24.  
  25. # 调用 update_many() 方法,则会将所有符合条件的数据都更新
  26. condition = {'age': {'$gt': 20}}
  27. result = collection.update_many(condition, {'$inc': {'age': 1}})
  28. print(result)
  29. print(result.matched_count, result.modified_count)

10.删除

  1. import pymongo
  2.  
  3. client = pymongo.MongoClient(host='localhost', port=27017)
  4. # client = MongoClient('mongodb://localhost:27017/')
  5. db = client.test
  6. # db = client['test']
  7. collection = db.students
  8.  
  9. # delete_one() 即删除第一条符合条件的数据,delete_many() 即删除所有符合条件的数据
  10. # 返回结果是 DeleteResult 类型,可以调用 deleted_count 属性获取删除的数据条数
  11.  
  12. result = collection.delete_one({'name': 'Mike'})
  13. print(result)
  14. print(result.deleted_count)
  15. result = collection.delete_many({'age': {'$lt': 25}})
  16. 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的更多相关文章

  1. 【网络爬虫入门05】分布式文件存储数据库MongoDB的基本操作与爬虫应用

    [网络爬虫入门05]分布式文件存储数据库MongoDB的基本操作与爬虫应用 广东职业技术学院  欧浩源 1.引言 网络爬虫往往需要将大量的数据存储到数据库中,常用的有MySQL.MongoDB和Red ...

  2. 04 爬虫数据存储之Mongodb

    MongoDB 认识MongoDB MongoDB是一个基于分布式文件存储的数据库.由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案.MongoDB是一个介于关系数据库和非关系数据 ...

  3. 爬虫文件存储:txt文档,json文件,csv文件

    5.1 文件存储 文件存储形式可以是多种多样的,比如可以保存成 TXT 纯文本形式,也可以保存为 Json 格式.CSV 格式等,本节我们来了解下文本文件的存储方式. 5.1.1 TXT文本存储 将数 ...

  4. 分布式文件存储数据库 MongoDB

    MongoDB 简介 Mongo 并非芒果(Mango)的意思,而是源于 Humongous(巨大的:庞大的)一词. MongoDB 是一个基于分布式文件存储的 NoSQL 数据库.由 C++ 语言编 ...

  5. 爬虫—文件存储—CSV存储

    一,简介 CSV,全称Comma—Separated Values,可以称为逗号分隔或者字符分隔值,其文件以纯文本形式存储表格数据.该文件是一个字符序列,可以有任意的数目记录组成,记录间已某种换行符分 ...

  6. 爬虫文件存储-3:Redis

    前提条件: 安装并运行redis服务端程序,安装RedisPy库 说明:Redis 是 StrictRedis 的子类,它的主要功能是用于向后兼容旧版本库里的几个方法,官方推荐使用 StrictRed ...

  7. 爬虫文件存储-1:mysql

    1.连接并创建数据库 import pymysql db = pymysql.connect(host='localhost', user='root', password='root', port= ...

  8. Python爬虫框架Scrapy实例(三)数据存储到MongoDB

    Python爬虫框架Scrapy实例(三)数据存储到MongoDB任务目标:爬取豆瓣电影top250,将数据存储到MongoDB中. items.py文件复制代码# -*- coding: utf-8 ...

  9. MongoDb gridfs-ngnix文件存储方案

          在各类系统应用服务端开发中,我们经常会遇到文件存储的问题. 常见的磁盘文件系统,DBMS传统文件流存储.今天我们看一下基于NoSQL数据库MongoDb的存储方案.笔者环境 以CentOS ...

随机推荐

  1. string转date

    /*util-->sql*/ java.util.Date utdt; java.sql.Date sqldt =null; SimpleDateFormat simFormat = new S ...

  2. RDA EQ&频响曲线

    相关数据: FAC->Audio->EQ Setting EQ Band - Gain Frequency Q Factor 1.5 FAC->Audio->PEQ // En ...

  3. MSP430:中断简介

    (5).中断应用程序举例(外部中断): void interrupt_initial() { P1DIR&=~BIT7;      //P1.7为输入 P1IE|=0x80;      //P ...

  4. ubuntu下设置共享目录

    在使用VirtualBox和相关的客户机系统比如XPMac等需要用到一些相关功能共享剪贴板等等这时候需要安装VirtualBox中的一个工具叫做Guest Additions中文叫法不一增强工具包功能 ...

  5. Oracle group by分组拼接字符串

    select wm_concat(id),depon  from test_1  group by depon

  6. TypeScript `infer` 关键字

    考察如下类型: type PromiseType<T> = (args: any[]) => Promise<T>; 那么对于符合上面类型的一个方法,如何得知其 Prom ...

  7. excel另存为csv

    # -*- coding: utf-8 -*- """ Created on Tue Jul 11 21:25:57 2017 import pandas as pd i ...

  8. JS高级——Function原型链

    基本概念 1.函数可以通过Function new出来,那么Function可以被称作构造函数,被new出来的函数可以被称为一个对象 2.Function既然是构造函数,那么肯定也有原型,它的原型是一 ...

  9. html——a标签中target属性

    有 4 个保留的目标名称用作特殊的文档重定向操作: _blank 浏览器总在一个新打开.未命名的窗口中载入目标文档. _self 这个目标的值对所有没有指定目标的 <a> 标签是默认目标, ...

  10. 控制台——EventLog实现事件日志操作

    我们应该如何通过写代码的方式向其中添加“日志”呢? 在操作之前,先明确几个概念: 1:事件日志名(logName):“事件查看器”中的每一项,如“应用程序”.“Internet Explorer”.“ ...