1. 安装MongoDB并启动服务,安装PyMongo
2. 连接MongoDB,并指定连接数据库、集合

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']

3. 插入

student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
'''
result = collection.insert(student)
print(result) #5932a68615c2606814c91f3d
result = collection.insert([student, student])
print(result) #[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]
'''
#PyMongo 3.x版本中推荐使用 insert_one、insert_many
result = collection.insert_one(student)
print(result.inserted_id)
result = collection.insert_many([student, student])
print(result.inserted_ids)

4. 查询

result = collection.find_one({'name': 'Mike'})
print(type(result)) #<class 'dict'>
print(result) from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')}) #查询指定id结果
print(result) results = collection.find({'age': 20}) #等值查询
results = collection.find({'age': {'$gt': 20}}) #大于20
results = collection.find({'name': {'$regex': '^M.*'}}) #正则,M开头
print(results) #cursor对象,相当于生成器
for result in results:
print(result)

5. 计数

count = collection.find().count()
count = collection.find({'age': 20}).count()
print(count)

6. 排序

results = collection.find().sort('name', pymongo.ASCENDING)  #DESCENDING
print([result['name'] for result in results])

7. 偏移

''' 忽略前N个元素,取几条

注意:在数据库数量非常庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,
因为这样很可能导致内存溢出。最好记录上次_id用条件查询
'''

results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])

8. 更新

'''
首先指定查询条件,然后将数据查询出来,修改年龄后调用update()方法将原条件和修改后的数据传入。
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result) #{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True} 这样可以只更新student字典内存在的字段。如果原先还有其他字段,则不会更新,也不会删除。
而如果不用$set的话,则会把之前的数据全部用student字典替换;如果原本存在其他字段,则会被删除。
result = collection.update(condition, {'$set': student})
''' # 推荐使用
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student}) condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}}) #年龄+1
#result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

9. 删除

'''result = collection.remove({'name': 'Kevin'})  #符合条件的所有记录'''
#推荐使用
result = collection.delete_one({'name': 'Kevin'})
result = collection.delete_many({'age': {'$lt': 25}})
print(result)
print(result.deleted_count)

10. 其他组合方法

create_index、create_indexes、drop_index
find_one_and_delete、find_one_and_replace、find_one_and_update

 

参考链接:

官方文档

转自:Python操作MongoDB看这一篇就够了

pymongo 笔记(转)的更多相关文章

  1. Pymongo 笔记

    Pymongo 1.MongoDB概念 MongoDB是一种非关系型数据库(NoSQL),MongoDB数据存储于内存,内存不足则将热度低数据写回磁盘.存储的数据结构为文档.每个数据库包含若干集合(c ...

  2. pymongo 3.3 使用笔记

    #首先安装pymongo sudo pip install pymongo || sudo easy_install pymongo #demo均在交互解释器下进行 from pymongo impo ...

  3. MongoDB学习笔记六:进阶指南

    [数据库命令]『命令的工作原理』MongoDB中的命令其实是作为一种特殊类型的查询来实现的,这些查询针对$cmd集合来执行.runCommand仅仅是接受命令文档,执行等价查询,因此,> db. ...

  4. 《Python 数据科学实践指南》读书笔记

    文章提纲 全书总评 C01.Python 介绍 Python 版本 Python 解释器 Python 之禅 C02.Python 基础知识 基础知识 流程控制: 函数及异常 函数: 异常 字符串 获 ...

  5. 学习笔记:python3,PIP安装第三方库(2017)

    https://pip.pypa.io/en/latest/quickstart/ pip的使用文档 http://www.lfd.uci.edu/~gohlke/pythonlibs/   .whl ...

  6. python高级编程读书笔记(一)

    python高级编程读书笔记(一) python 高级编程读书笔记,记录一下基础和高级用法 python2和python3兼容处理 使用sys模块使程序python2和python3兼容 import ...

  7. python学习笔记比较全

    注:本笔记基于python2.6而编辑,尽量的偏向3.x的语法 Python的特色 1.简单 2.易学 3.免费.开源 4.高层语言: 封装内存管理等 5.可移植性: 程序如果避免使用依赖于系统的特性 ...

  8. 笔记-python lib-pymongo

    笔记-python lib-pymongo 1.      开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...

  9. Scrapy笔记06- Item Pipeline

    Scrapy笔记06- Item Pipeline 当一个item被蜘蛛爬取到之后会被发送给Item Pipeline,然后多个组件按照顺序处理这个item. 每个Item Pipeline组件其实就 ...

随机推荐

  1. Codeforces Round #594 (Div. 2)

    传送门 C. Ivan the Fool and the Probability Theory 题意: 给出一个\(n*m\)的方格,现在要给方格中的元素黑白染色,要求任一颜色最多有一个颜色相同的格子 ...

  2. 使用 github pages快速部署自己的静态网页

    看见很多大神在Github Pages上部署Demo,感觉效果还不错,刚才自己也试了一下,发现其实并不难! 选择 github pages 的理由 使用零成本: github pages 集成在 gi ...

  3. c语言文件

    完整代码块展示: #include <stdio.h> #include <stdlib.h> #include <string.h> struct student ...

  4. Nacos做配置中心经常被问到的问题

    加载多个配置文件怎么处理? 通过@NacosPropertySource可以注入一个配置文件,如果我们需要将配置分类存储或者某些配置需要共用,这种需求场景下,一个项目中需要加载多个配置文件,可以可以直 ...

  5. Python必备收藏!博士大佬总结的Pycharm 常用快捷键思维导图

    ​ 搜索 Ctrl + Shift + F7用法高亮显示 Ctrl + Alt + F7显示用法 编辑 ​ Ctrl + Shift + V从最近的缓冲区粘贴 Ctrl + D复制选定的区域或行到后面 ...

  6. RMAN详细教程(四):备份脚本实战操作

    RMAN详细教程(一):基本命令代码 RMAN详细教程(二):备份.检查.维护.恢复 RMAN详细教程(三):备份脚本的组件和注释 RMAN详细教程(四):备份脚本实战操作 1.为了安全起见,先将数据 ...

  7. IT从业者不可不知的三条定律

    信息技术行业,也就是我们所说的IT行业,有着传统行业所未有的发展速度和模式,当然也有着它独特的发展定律.如果你是从事相关行业,下面讲到的三条定律,不可不知. 摩尔定律 比尔·盖茨曾跟通用公司老板说:如 ...

  8. 近日LeetCode算法(记录)

    近日LeetCode算法 前言:最近刷了好多leetcode算法题,大家知道,程序=数据结构+算法,由此可见,算法真的是很重要的呢.闲话少谈,切入正题,来看看小编觉得有点意思的5题算法题吧... 1. ...

  9. C#简单的枚举及结构

    using System; namespace program { enum WeekDays { a, b, c = ,//11 赋值以后就变成11,不赋值就是2 d, e, f, g }//不能输 ...

  10. .net 数据源DataSet 转换成模型

    /// <summary> /// DataSet转换成model 自动赋值返回集合 /// </summary> /// <typeparam name="T ...