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. centos7服务器监控之nmon

    一.下载nmon 根据系统类型下载相应的版本: http://nmon.sourceforge.net/pmwiki.php?n=Site.Download 目前大多数服务器使用的centos7系统, ...

  2. Ubuntu18.04初始化

    Ubuntu18.04初始化 更新源: sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak sudo gedit /etc/apt/sour ...

  3. Linux下基于shell脚本实现学生信息管理系统

    #该管理系统是参考两位博主(时间有点远了,我忘了,请博主看到后联系我)后自行修改添加的.登录过程还有很多不完善,我就抛砖引玉啦. 废话不多,直接上码! #!/bin/bash# 学生管理系统# @ve ...

  4. crossover mac如何使用?crossover mac使用教程

    CrossOver Mac 破解版可以在 Mac 上运行成千上万的 Windows 程序,从办公软件.实用工具.游戏到设计软件.CrossOver 19 破解版可以让 Windows 程序和 Mac ...

  5. poj 3253 Fence Repair 贪心 最小堆 题解《挑战程序设计竞赛》

    地址 http://poj.org/problem?id=3253 题解 本题是<挑战程序设计>一书的例题 根据树中描述 所有切割的代价 可以形成一颗二叉树 而最后的代价总和是与子节点和深 ...

  6. 算法问题实战策略 SORTGAME

    地址 https://algospot.com/judge/problem/read/SORTGAME 解答 常规BFS是会超时的  按照书上的提示 应该是打表(居然还有提倡打表的题目) tle 代码 ...

  7. 在Ubuntu环境下配置Proxmark3(PM3)使用环境

    参考资料:PM3官方Wiki 因为国内网络上大多是在Kali系统上使用PM3的教程(链接1.链接2.链接3),而这些教程的步骤对于Ubuntu系统并不完全适用.所以写下本文,记录我个人的安装经历. 本 ...

  8. 80道最新java基础部分面试题(五)

    自己整理的面试题,希望可以帮到大家,需要更多资料的可以私信我哦,大家一起学习进步! 48.同步和异步有何异同,在什么情况下分别使用他们?举例说明.  如果数据将在线程间共享.例如正在写的数据以后可能被 ...

  9. SpringBootTest MockMVC绑定session(需要登陆的接口)

    https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testing spring-te ...

  10. Python ASCII码与字符相互转换

    ASCII ((American Standard Code for Information Interchange): 美国信息交换标准代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和 ...