• MongoDB操作、非关系型数据库存储


    关系型数据库存储

    • NoSQL

      • 模型非关系型
      • 可以存储JSON、键值对等(取决于NoSQL数据库类型)
      • 并不是每条记录都要有相同的结构
      • 添加带有新属性的数据时,不会影响其他
      • 支持ACID事务,根据使用的NoSQL的数据库而有所不同
      • 一致性可以改变
      • 横向扩展能力

    对于爬虫的数据存储来说,一条数据可能存在某些字段提取失败而缺失的情况,而且数据可能随时调整。另外,数据之间还存在嵌套关系。如果使用关系型数据库存储,一是需要提前建表,二是如果存在数据嵌套关系的话,需要进行序列化操作才可以存储,这非常不方便。如果用了非关系型数据库,就可以避免一些麻烦,更简单高效

    MongoDB 是由 C++ 语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似 JSON 对象,它的字段值可以包含其他文档、数组及文档数组,非常灵活。在这一节中,我们就来看看 Python 3 下 MongoDB 的存储操作

    1. 准备工作

    • 确保MongoDB已安装并启动服务
    • 安装pymongo库

    2. 连接MongoDB

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

    import pymongo
    client = pymongo.MongoClient(host = "localhost",port = 27017)
    
    • 1
    • 2

    3.指定数据库

    MongoDB 中可以建立多个数据库,接下来我们需要指定操作哪个数据库。这里我们以 test 数据库为例来说明,下一步需要在程序中指定要使用的数据库

    db = client.test
    
    • 1

    这里调用 client 的 test 属性即可返回 test 数据库

    db = client['test']
    
    • 1

    4. 指定集合

    MongoDB 的每个数据库又包含许多集合(collection),它们类似于关系型数据库中的表。

    下一步需要指定要操作的集合,这里指定一个集合名称为 students。与指定数据库类似,指定集合也有两种方式:

    # 声明了一个 Collection 对象
    # collection.drop()
    collection = db.students
    
    • 1
    • 2
    • 3
    collection = db['students']
    
    • 1

    5. 插入数据

    # 新建数据集
    student = {
        'id': '20170101',
        'name': 'Jordan',
        'age': 20,
        'gender': 'male'
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    # 直接调用 collection 的 insert() 方法即可插入单条数据
    result = collection.insert(student)
    print(result)
    
    • 1
    • 2
    • 3

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

    # 插入多条数据
    student1 = {
        'id': '20170101',
        'name': 'Jordan',
        'age': 20,
        'gender': 'male'
    }
    
    student2 = {
        'id': '20170202',
        'name': 'Mike',
        'age': 21,
        'gender': 'male'
    }
    
    result = collection.insert([student1, student2])
    print(result)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    返回结果是对应的_id 的集合

    实际上,在 PyMongo 3.x 版本中,官方已经不推荐使用 insert() 方法了。当然,继续使用也没有什么问题。官方推荐使用 insert_one() 和 insert_many() 方法来分别插入单条记录和多条记录

    student = {
        'id': '20170101',
        'name': 'Jordan',
        'age': 20,
        'gender': 'male'
    }
    
    result = collection.insert_one(student)
    print(result)
    print(result.inserted_id)
    # 与 insert() 方法不同,这次返回的是 InsertOneResult 对象,我们可以调用其 inserted_id 属性获取_id
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    student1 = {
        'id': '20170101',
        'name': 'Jordan',
        'age': 20,
        'gender': 'male'
    }
    
    student2 = {
        'id': '20170202',
        'name': 'Mike',
        'age': 21,
        'gender': 'male'
    }
    
    result = collection.insert_many([student1, student2])
    print(result)
    print(result.inserted_ids)
    # 该方法返回的类型是 InsertManyResult,调用 inserted_ids 属性可以获取插入数据的_id 列表
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    6.查询

    插入数据后,我们可以利用 find_one() 或 find() 方法进行查询,其中 find_one() 查询得到的是单个结果,find() 则返回一个生成器对象

    result = collection.find_one({'name': 'Mike'})
    print(type(result))
    print(result)
    
    • 1
    • 2
    • 3

    也可以根据 ObjectId 来查询,此时需要使用 bson 库里面的 objectid

    from bson.objectid import ObjectId
    
    result = collection.find_one({'_id': ObjectId('616157f33e18aab81056be75')})
    print(result)
    
    • 1
    • 2
    • 3
    • 4

    对于多条数据的查询,我们可以使用 find() 方法

    # 查询年龄大于 20 的数据
    # 查询的条件键值已经不是单纯的数字了,而是一个字典,其键名为比较符号 $gt,意思是大于,键值为 20
    results = collection.find({'age': {'$gt': 20}})
    [print(result) for result in results]
    
    • 1
    • 2
    • 3
    • 4
    # 正则匹配查询
    # 查询名字以 M 开头的学生数据
    results = collection.find({'name': {'$regex': '^M.*'}})
    [print(result) for result in results]
    
    • 1
    • 2
    • 3
    • 4

    比较符号

    符号含义示例
    $lt小于{‘age’:{‘$lt’:20}}
    $gt大于{‘age’:{‘$gt’:20}}
    $lte小于等于{‘age’:{‘$lte’:20}}
    $gte大于等于{‘age’:{‘$gte’:20}}
    $ne不等于{‘age’:{‘$ne’:20}}
    $in在范围内{‘age’:{‘$in’:20}}
    $nin不在范围内{‘age’:{‘$nin’:20}}

    功能符号

    符号含义示例
    $regex匹配正则表达式{‘name’: {‘$regex’: ‘^M.*’}}
    $exists属性是否存在{‘name’: {‘$exists’: True}}
    $type类型判断{‘age’:{‘$type’:‘int’}}
    $mod数字模操作{‘age’:{‘$mode’:[5,0]}}
    $text文本查询{‘$text’:{‘$search’:‘Mike’}}
    $where高级条件查询{‘$where’:‘obj.fans_count == obj.follows_count’}

    7 计数、排序、偏移

    • 要统计查询结果有多少条,可以调用count()方法
    • 要排序,调用sort()方法,传入升序标志:pymongo.ASCENDING,降序标志:pymongo.DESCENDING
    • 只提取结果中的几个元素,调用skip()方法偏移几个位置;只提取几个结果,调用limit()方法
    #统计所有数据条数
    count = collection.find().count()
    print(count)
    
    • 1
    • 2
    • 3
    #统计符合某个条件的数据
    count = collection.find({'age': 20}).count()
    print(count)
    
    • 1
    • 2
    • 3
    # 排序
    results = collection.find().sort('name', pymongo.ASCENDING)
    print([result['name'] for result in results])
    
    • 1
    • 2
    • 3
    # 偏移
    results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
    print([result['name'] for result in results])
    
    • 1
    • 2
    • 3
    #偏移+限制
    results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
    print([result['name'] for result in results])
    
    • 1
    • 2
    • 3

    8.更新

    对于数据更新,我们可以使用 update() 方法,指定更新的条件和更新后的数据即可

    condition = {'name': 'Jordan'}
    student = collection.find_one(condition)
    student['age'] = 25
    result = collection.update(condition, student)
    print(result)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    我们也可以使用$set 操作符对数据进行更新.这样可以只更新 student 字典内存在的字段。如果原先还有其他字段,则不会更新,也不会删除。而如果不用 $set 的话,则会把之前的数据全部用 student 字典替换;如果原本存在其他字段,则会被删除

    result = collection.update(condition, {'$set': student})
    
    • 1

    update() 方法其实也是官方不推荐使用的方法。这里也分为 update_one() 方法和 update_many() 方法,用法更加严格,它们的第二个参数需要使用 $ 类型操作符作为字典的键名,示例如下

    condition = {'name': 'Kevin'}
    student = collection.find_one(condition)
    student['age'] = 26
    result = collection.update_one(condition, {'$set': student})
    print(result)
    print(result.matched_count, result.modified_count)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    里调用了 update_one() 方法,第二个参数不能再直接传入修改后的字典,而是需要使用 {‘$set’: student} 这样的形式,其返回结果是 UpdateResult 类型。然后分别调用 matched_count 和 modified_count 属性,可以获得匹配的数据条数和影响的数据条数

    9. 删除

    删除操作比较简单,直接调用 remove() 方法指定删除的条件即可,此时符合条件的所有数据均会被删除

    result = collection.remove({'name': 'Kevin'})
    print(result)
    
    • 1
    • 2

    另外,这里依然存在两个新的推荐方法 ——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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    剖析虚幻渲染体系(14)- 延展篇:现代渲染引擎演变史Part 1(萌芽期)
    apache和IIS区别?内网本地服务器项目怎么让外网访问?
    level2接口有什么用?是如何获取A股行情数据的?
    03- LSTM 的从零开始实现
    基于Infineon开发板实现RT-Thread物联网 DEMO
    Vue-dvadmin-d2-crud-plus-常用配置-row-handle-columns-options
    Linux内存管理(1):memblock
    Docker基本原理
    外包干了3天,技术退步明显.......
    MyBatis简介测试
  • 原文地址:https://blog.csdn.net/weixin_45934622/article/details/127845793