如何用python 操作MongoDB数据库
作者:三只松鼠 发布时间:2024-01-27 16:53:10
目录
一、前言
二、操作 MongoDB
1、安装 pymongo
2、连接 MongoDB
3、选择数据库
4、选择集合
5、插入数据
6、查询
7、更新数据
8、删除
一、前言
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}
来源:https://www.cnblogs.com/shenh/p/14416111.html


猜你喜欢
- 120726 11:57:22 [Warning] 'user' entry 'root@localhost.loc
- 一、管理数据库连接1、使用配置文件管理连接之约定在数据库上下文类中,如果我们只继承了无参数的DbContext,并且在配置文件中创建了和数据
- 一、简介pydantic 库是 python 中用于数据接口定义检查与设置管理的库。pydantic 在运行时强制执行类型提示,并在数据无效
- 一、KNN算法简介邻近算法,或者说K最近邻(kNN,k-NearestNeighbor)分类算法是数据挖掘分类技术中最简单的方法之一。所谓K
- 本文实例为大家分享了python实现文件批量重命名,供大家参考,具体内容如下讲解1、库:os2、代码效果:对指定文件夹内所有文件重命名为1,
- 说检查点,其实就是对过去历史的记录,可以认为是log.不过这里进行了简化.举例来说,我现在又一段文本.文本里放有一堆堆的链接地址.我现在的任
- 一、前言昨夜刷b站的时候,看到了一条评论,形式如下图,于是心血来潮写了个python脚本,可以根据文字来生成这种由emoji拼接成的“文字”
- 老声长谈,着是困惑很多人的问题,如果处理不好,都是乱码,说这些话并不是我对编码很精通,只是在这方面是得留神,自己总结了一点小经验(容易出现乱
- Flask 是一个 Python 实现的 Web 开发微框架。这篇文章是一个讲述如何用它实现传送视频数据流的详细教程。我敢肯定,现在你已经知
- 诈尸人口回归。这一年忙着灌水忙到头都掉了,最近在女朋友的提醒下终于想起来博客的账号密码,正好今天灌水的时候需要画一个双X轴双Y轴的图,研究了
- DataFrame的行和列:df[‘行’, ‘列’]Data
- 用鼠标双击需要更改的变量,就会将其选中,选中的标志是相应变量名有了色块然后右键点击这个变量,找到Refactor,然后再选择Reanme然后
- 在日常工作中,可能会遇到各类表格合并的需求。这类需求只要搞懂核心原理都很简单,本质都是万变不离其宗,相信大部分读者都能解决大部分需求。基本思
- 本文介绍一种将一个大的文本文件分割成多个小文件的方法方法一:1.读取文章所有的行,并存入列表中2.定义分割成的小文本的行数3.将原文本内容按
- 适用环境: PHP5.2.x / mysql 5.0.xclass Mysql { priva
- 本文实例讲述了JS定义函数的几种常用方法。分享给大家供大家参考,具体如下:在 JavaScript 语言里,函数是一种对象,所以可以说函数是
- 参数数量及其作用该函数共有十一个参数,常用的有:名称 name变量规格 shape变量类型 dtype变量初始化方式 initializer
- 无论你在linux上娱乐还是工作,这对你而言都是一个使用python来编程的很好的机会。回到大学我希望他们教我的是Python而不是Java
- 因为写别的程序想要一边遍历一边删除列表里的元素,就写了一个这样的程序进行测试,这样写出来感觉还挺简洁的,就发出来分享一下。代码l=list(
- 本文实例为大家分享了java模拟ATM功能的具体代码,供大家参考,具体内容如下有三个类:Test.java、Customer.java、Cu