Python3中PyMongo使用举例
MongoDB是一个基于分布式文件存储的开源数据库,由C++语言编写,与平台无关,旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
在Python中操作MongoDB可以使用PyMongo,在ubuntu上安装PyMongo,执行:$ python3 -m pip install pymongo ,结果如下图所示:
在ubuntu上安装MongoDB,执行:$ sudo apt-get install mongodb ,这样在14.04上默认安装的是2.4.9版本,安装完后默认启动服务,但是之前我们安装pymongo时是3.7.2版本,这样导致pymongo与mongo不匹配,即出现” pymongo.errors.ConfigurationError: Server at localhost:27017 reports wire version 0, but this version of PyMongo requires at least 2 (MongoDB 2.6).”的错误,解决方法可以是降低pymongo的版本,或者升级mongo的版本。在ubuntu安装高版本的mongodb可以参考:https://docs.mongodb.com/v2.6/tutorial/install-mongodb-on-ubuntu/ ,这里为了简便,降低pymongo的版本,从3.7.2降低到3.4.0,执行命令:conda install pymongo=3.4.0 。
测试代码如下:
import pymongo'''
reference:https://juejin.im/post/5addbd0e518825671f2f62eehttp://www.runoob.com/python3/python-mongodb.htmlhttps://blog.csdn.net/xsdxs/article/details/52565489
'''def print_results(description, results):strs = description + " type:"print(strs, type(results))description += ":"if (isinstance(results, dict)):print(description, results)else: for result in results:print(description, result)if __name__ == "__main__":print("pymongo version:", pymongo.version)client = pymongo.MongoClient(host='localhost', port=27017) # mongodb默认端口是27017print("connection successed:", client.server_info()) # 判断是否连接成功db = client.test # 指定test数据库, 如果没有则会自动创建collection = db.students # 每个数据库又包含许多集合student1 = {'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}result = collection.insert_one(student1) # 在students集合中插入一条学生数据print("insert result:", result)student2 = {'id': '20170102', 'name': 'Tom', 'age': 21, 'gender': 'male'}student3 = {'id': '20170203', 'name': 'Mike', 'age': 22, 'gender': 'male'}result = collection.insert_many([student2, student3]) # 在students集合中插入多条学生数据print("many insert result:", result)result = collection.find_one({"name": "Tom"}) # 查询单个结果print_results("find one result", result)results = collection.find({"age": 20}) # 查询多个结果print_results("find many results", results)results = collection.find({"age": {"$gt": 20}}) # 查询年龄大于20的多个结果print_results("find age > 20 many results", results)count = collection.find({"age": 20}).count() # 查询计数print("find result count:", count)result = collection.delete_one({"age": 21}) # 删除一条数据print("delete one result:", result)print("delete one result count:", result.deleted_count)results = collection.delete_many({"age": {"$gte": 21}})print("delete many results:", results)print("delete many results count", results.deleted_count)condition = {"name": "Jordan"}student = collection.find_one(condition)#print_results("find one result", student)student["age"] = 25result = collection.update(condition, student) # 更新一条数据print("update result:", result)print("db collection names:", db.collection_names()) # 查看test数据库下所有表名称dblist = client.database_names() # 获取mongodb下所有数据库print("db list names:", dblist)
执行结果如下:
GitHub:https://github.com/fengbingchun/Python_Test
Python3中PyMongo使用举例相关推荐
- python3中使用subprocess模块执行外部命令
一. subprocess模块介绍 subprocess模块可以替代os模块下的os.system和os.popen等操作方法 subprocess模块在python2和python3上的使用上有一定 ...
- python3中reduce函数的使用
在python3中如果使用reduce需要先导入 from functools import reduce reduce函数,reduce函数会对参数序列中元素进行累积. reduce函数的定义: r ...
- Python2和Python3中@abstractmethod的用法
抽象方法: 抽象方法表示基类的一个方法,没有实现,所以基类不能实例化,子类实现了该抽象方法才能被实例化. Python的abc提供了@abstractmethod装饰器实现抽象方法,下面以Python ...
- python3中数字类型有哪些_Python3数据类型—列表 | 吴老二
变量 在没有说数据类型之前,先简单说一下变量.后面会对变量有补充,变量是什么,简单的说就是内存地址的名字.举个例子,wulaoer="吴老二",这就是一个变量,中文"吴老 ...
- python3中argparse模块详解
文章目录 python3中argparse模块详解 一. 命令行参数分为位置参数和选项参数: 二. 使用步骤: 三. add_argument()方法参数: 1. name or flags: 2. ...
- 对python3中pathlib库的Path类的使用详解
原文连接 https://www.jb51.net/article/148789.htm 1.调用库 ? 1 from pathlib import 2.创建Path对象 ? 1 2 3 4 5 ...
- Python3中typing模块介绍
typing.py的源码在:https://github.com/python/cpython/blob/main/Lib/typing.py.此模块为类型提示(Type Hints)提供运行时支持( ...
- Python3中内置函数callable介绍
Python3中的内置函数callable接受一个对象参数,如果此对象参数看起来可调用,则callable函数返回True,否则返回False.如果返回True,则调用仍有可能失败:但如果 ...
- Python3中lambda表达式介绍
Python3中的lambda表达式或lambda函数是匿名函数(anonymous function),意味着该函数没有名称.def关键字用于在Python3中创建一个普通函数,类似地,lambda ...
最新文章
- mysql pos点是什么,MySQL 5.6 主从报错一例
- CentOS 7最小化安装步骤
- 交换机是如何对数据包打标签去标签的_如何使用PC抓带vlan标签的数据包?王海军老师告诉你...
- AI与医学:AI预测结合医学案例应用——当基因编辑转角遇到AI
- PROCESSES, SESSIONS和CONNECTIONS的区别
- Request.InputStream 将数据作为XML数据发送
- 2020\Simulation_2\1.12.5MB
- 批处理 正则表达式(findstr) 整理
- qt服务器获取formdata文件,QT上传(PUT)文件
- Python操作文件,报FileNotFoundError: [Error 2] No such file or directory错误
- 2.5D休闲娱乐生活类插画素材,给设计添彩!
- win7 oracle数据库删除用户名,win7操作系统、 oracle10g 数据库创建、卸载 用户名的创建 、删除...
- EasyRecovery如何恢复系统镜像
- 量子计算机解ns方程,量子计算机可解方程组
- 基于qt的贪吃蛇游戏 c语言,基于QT的贪吃蛇游戏设计
- Vivado2017.4软件安装
- 基于浏览器的3D网页游戏JavaScript 3D游戏引擎介绍
- Linux安装Perl(最新版)
- 阿拉伯文变形规范,阿拉伯语变形规则,阿拉伯文组合规则
- 医学图像——CT值(Hu值)