zoukankan      html  css  js  c++  java
  • Pymongo 笔记

    Pymongo

    1、MongoDB概念

    MongoDB是一种非关系型数据库(NoSQL),MongoDB数据存储于内存,内存不足则将热度低数据写回磁盘。存储的数据结构为文档。每个数据库包含若干集合(collection),集合又包含文档。
    集合相当于SQL中的表的功能,可以使用集合对文档进行分组。
    文档中包含多组键值对(BSON),值可为多种类型、其他文档或者文档数组等等。
    字段即键值对。

    2、Pymongo基本操作

    连接MongoDB:

    client = pymongo.MongoClient(host='127.0.0.1', port=27017)
    

    选择数据库school:

    db = client['school']
    

    选择集合class:

    collection = db['class']
    

    插入数据:

    student = {
    	'name':'zhangsan',
    	'age':15
    }
    res = collection.insert_one(student)
    res = collection.insert_many([student, student, student])
    

    查询:
    使用find_one查询返回一个满足要求的文档(字典类型),无则返回None。
    使用find查询返回所有满足要求的文档(Cursor类型),无则返回None。
    查询还可以按照规则查,诸如大于、小于、不等于、在...之内。
    查询规则doc

    # 查询一个满足age=12的文档
    res = collection.find_one({'age':12})
    
    # 查询所有满足age=12的文档
    res = collection.find({'age':12})
    for re in res:
    	print(re) # type(re) == dict
    
    # 查询所有age>12的文档
    res = collection.find({'age':{'$gt':12}})
    

    更新:
    使用update进行更新。
    如下调用直接把name=zhangsan的文档全部替换为后面的,有其他字段直接替换之后就没了。

    res = collection.update({'name':'zhangsan', {'age':13,'name':'zhangsan'}})
    

    使用$set如果之前还有其他字段,name就会保留,只会更新给出的字段。

    res = collection.update_one({'name':'zhangsan', {'$set':{'age':13}}})
    

    update也支持根据规则更新。

    删除:
    使用remove根据规则删除。

    res = collection.delete_one({'age':12})
    res = collection.delete_many({'age':13})
    
  • 相关阅读:
    【人生苦短,我学Python】个人学习笔记——str.count方法
    微信支付问题解决
    针对listview上面的按钮点击事件的操作
    Android界面之间的跳转和返回
    贪吃蛇
    数据库的连接
    Android中实现圆的面积的计算问题
    关于安卓环境的搭建问题
    python 获取cpu、内存、硬盘等实时信息 psutil
    python 配置文件
  • 原文地址:https://www.cnblogs.com/KirinSB/p/13528927.html
Copyright © 2011-2022 走看看