如何用python 操作MongoDB数据库
一、前言
MongoDB属于 NoSQL(非关系型数据库),是一个基于分布式文件存储的开源数据库系统。
二、操作 MongoDB
1、安装 pymongo
python 使用第三方库来连接操作 MongoDB,所以我们首先安装此库。
pip3 install pymongodb
2、连接 MongoDB
使用 MongoClient 类连接,以下两种参数方式都可以:
from pymongo import MongoClient # 连接方式一 client = MongoClient(host='localhost',port=27017) # 连接方式二 # client = MongoClient('mongodb://localhost:27017/')
3、选择数据库
MongoDB 可以创建很多 db,指定我们需要的 db 即可
# 方式一 db = client.Monitor # 方式二 # db = client['Monitor']
4、选择集合
db 内包含很多个集合,有点类似 mysql 这类关系型数据库中的表
# 方式一 collection = db.test # 方式二 # collection = db['test']
5、插入数据
插入一条数据,MongoDB 每条记录都有一个唯一标识。返回一个 InsertOneResult 对象,若需要获取唯一标识,找到 InsertOneResult 对象的属性 inserted_id 即可
from pymongo import MongoClient class mongodb: def __init__(self,host,db,port = 27017): ''' :param host: str mongodb地址 :param db: str 数据库 :param port: int 端口,默认为27017 ''' host = host db = db self.port = port client = MongoClient(host=host,port=port) self.db = client[db] def insert_one(self,table,dic): ''' :param table: str 数据库中的集合 :param dic: dict 要插入的字典 :return: 返回一个包含ObjectId类型的对象 ''' collection = self.db[table] rep = collection.insert_one(dic) return repif __name__=='__main__': dic = {'姓名':'小明','English':100,'math':90} db = mongodb(host='localhost',db = 'test') rep = db.insert_one('test',dic) print(rep.inserted_id)
插入多条数据,使用 insert_many 批量插入
from pymongo import MongoClient class mongodb: def __init__(self,host,db,port = 27017): ''' :param host: str mongodb地址 :param db: str 数据库 :param port: int 端口,默认为27017 ''' host = host db = db self.port = port client = MongoClient(host=host,port=port) self.db = client[db] def insert_one(self,table,dic): ''' :param table: str 数据库中的集合 :param dic: dict 要插入的字典 :return: 返回包含一个ObjectId类型的对象 ''' collection = self.db[table] rep = collection.insert_one(dic) return rep def insert_many(self,table,lists): ''' :param table: str 数据库中的集合 :param dic: dict 要插入的列表,列表中的元素为字典 :return: 返回包含多个ObjectId类型的列表对象 ''' collection = self.db[table] rep = collection.insert_many(lists) return rep if __name__=='__main__': lists = [{'姓名':'小明','English':100,'math':90}, {'姓名':'小华','English':90,'math':100}] db = mongodb(host='localhost',db = 'test') rep = db.insert_many('test',lists) for i in rep.inserted_ids: print(i)
6、查询
1)常规查询
- find_one :查询单条记录,返回一个字典。
- find:查询多条记录 ,返回一个游标对象。
from pymongo import MongoClient class mongodb: def __init__(self,host,db,port = 27017): ''' :param host: str mongodb地址 :param db: str 数据库 :param port: int 端口,默认为27017 ''' host = host db = db self.port = port client = MongoClient(host=host,port=port) self.db = client[db] def find_one(self,table,dic): ''' :param table: str 数据库中的集合 :param dic: dict 查询条件 :return: dict 返回单条记录的字典 ''' collection = self.db[table] rep = collection.find_one(dic) return rep def find(self,table,dic): ''' :param table: str 数据库中的集合 :param dic: dict 查询条件 :return: list 返回查询到记录的列表 ''' collection = self.db[table] rep = list(collection.find(dic)) return rep if __name__=='__main__': # 查询 English 成绩为 100 的所有记录 dic = {'English':100} db = mongodb(host='localhost',db = 'test') rep = db.insert_many('test',dic) print(rep)
2)范围查询
有时候我们需要范围比较查询,比如要查询 English 成绩为 80~90 ,可以使用比较符:dic = {'English':{'$in':[80,90]}}
- $lt :小于
- $lte:小于等于
- $gt:大于
- $gte:大于等于
- $ne:不等于
- $in:在范围内
- $nin:不在范围内
3)计数
直接调用 count() 方法,返回一个 int 类型的数字
# 计数查询只需要在普通查询后加上 count() 即可 count = collection.find().count() # count = collection.find({'English':{'$gt':90}}).count()
4)排序
排序时,直接调用sort()方法,并在其中传入排序的字段及升降序标志,返回一个游标对象
# 正序 ASCENDING,倒序 DESCENDING。list()将游标对象转成列表 data = list(collection.find(dic).sort('姓名',pymongo.DESCENDING))
7、更新数据
首选查到需要更新的数据,然后将该数据更新,返回一个 UpdataResult 对象, raw_result 属性中包含 update 生效的个数。
- update_one:更新查询到的第一条数据
- update_many:更新多条数据
from pymongo import MongoClient class mongodb: def __init__(self,host,db,port = 27017): ''' :param host: str mongodb地址 :param db: str 数据库 :param port: int 端口,默认为27017 ''' host = host db = db self.port = port client = MongoClient(host=host,port=port) self.db = client[db] def update_one(self,table,condition,dic): ''' :param table: str 数据库中的集合 :param condition: dict 查询条件 :param dic: dict 更新的数据 :return: 返回UpdateResult对象 ''' collection = self.db[table] # $set 表示只更新dic字典内存在的字段 rep = collection.update_one(condition,{'$set':dic}) # 会把之前的数据全部用dic字典替换,如果原本存在其他字段,则会被删除 # rep = collection.update_one(condition, dic) return rep def update_many(self,table,condition,dic): ''' :param table: str 数据库中的集合 :param condition: dict 查询条件 :param dic: dict 更新的数据 :return:返回UpdateResult对象 ''' collection = self.db[table] # $set 表示只更新dic字典内存在的字段 rep = collection.update_many(condition,{'$set':dic}) # 会把之前的数据全部用dic字典替换,如果原本存在其他字段,则会被删除 # rep = collection.update_many(condition, dic) return rep if __name__=='__main__': condition = {'English':80} dic = {'English':60} db = mongodb(host='mongodb-monitor.monitor.svc.test.local',db = 'test') rep = db.update_one('test',condition,dic) print(rep.raw_result) # 输出 {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
8、删除
删除和 update 类似,删除数据后,返回一个 DeleteResult 对象, raw_result 属性中包含 delete 的个数
- delete_one:删除查询到的第一条数据
- delete_many:批量删除符合查询条件的数据
from pymongo import MongoClient class mongodb: def __init__(self,host,db,port = 27017): ''' :param host: str mongodb地址 :param db: str 数据库 :param port: int 端口,默认为27017 ''' host = host db = db self.port = port client = MongoClient(host=host,port=port) self.db = client[db] def delete_one(self,table,dic): ''' :param table: str 数据库中的集合 :param dic: dict 查询条件 :return: 返回DeleteResult对象 ''' collection = self.db[table] rep = collection.delete_one(dic) return rep def delete_many(self,table,dic): ''' :param table: str 数据库中的集合 :param dic: dict 查询条件 :return: 返回DeleteResult对象 ''' collection = self.db[table] rep = collection.delete_many(dic) return rep if __name__=='__main__': dic = {'English':60} db = mongodb(host='localhost',db = 'test') rep = db.delete_many('test',dic) print(rep.raw_result) # 输出 {'n': 21, 'ok': 1.0}
以上就是如何用python 操作MongoDB数据库的详细内容,更多关于python 操作MongoDB数据库的资料请关注猪先飞其它相关文章!
相关文章
- 这篇文章主要介绍了python-opencv-画外接矩形框的实例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
- 由于要使用mikoomi mongodb plugin插件,所以需要php对mongodb的扩展支持,默认通过源安装的php并没有mongodb的扩展支持,具体可以通过php -m|grep mongo 验证 。这里就结...2016-11-25
- 操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
Python astype(np.float)函数使用方法解析
这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08- 2022虎年新年即将来临,小编为大家带来了一个利用Python编写的虎年烟花特效,堪称全网最绚烂,文中的示例代码简洁易懂,感兴趣的同学可以动手试一试...2022-02-14
- 在本篇文章里小编给大家分享的是一篇关于python中numpy.empty()函数实例讲解内容,对此有兴趣的朋友们可以学习下。...2021-02-06
- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
python-for x in range的用法(注意要点、细节)
这篇文章主要介绍了python-for x in range的用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-05-10- 这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
- 这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
- 这篇文章主要介绍了python如何实现b站直播自动发送弹幕,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下...2021-02-20
- 这篇文章主要介绍了Intellij IDEA连接Navicat数据库的方法,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借价值,需要的朋友可以参考下...2021-03-25
- 在开发过程中,我们经常会将日期时间的毫秒数存放到数据库,但是它对应的时间看起来就十分不方便,我们可以使用一些函数将毫秒转换成date格式。 一、 在MySQL中,有内置的函数from_unixtime()来做相应的转换,使用如下: 复制...2014-05-31
python Matplotlib基础--如何添加文本和标注
这篇文章主要介绍了python Matplotlib基础--如何添加文本和标注,帮助大家更好的利用Matplotlib绘制图表,感兴趣的朋友可以了解下...2021-01-26- C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
- 这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
- 通过内网连另外一台机器的mysql服务, 确发现速度N慢! 等了大约几十秒才等到提示输入密码。 但是ping mysql所在服务器却很快! 想到很久之前有过类似的经验, telnet等一些服务在连接请求的时候,会做一些反向域名解析(如果...2015-10-21
- 今天小编就为大家分享一篇python 计算方位角实例(根据两点的坐标计算),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
- 某些时候,例如为了搭建一个测试环境,或者克隆一个网站,需要复制一个已存在的mysql数据库。使用以下方法,可以非常简单地实现。假设已经存在的数据库名字叫db1,想要复制一份,命名为newdb。步骤如下:1. 首先创建新的数据库newd...2015-10-21