Python+MongoDb使用手册(精简)

这里是学了下面链接的内容,加上一些自己学习的内容综合的,大家也可以去看看这篇文章,写的特别好 【python】在Python中操作MongoDB的详细用法教程与实战案例分享_python轻松入门,基础语法到高阶实战教学-CSDN专栏

1 库:pymongo

pip install pymongo

2 连接:MongoClient

from pymongo import MongoClient

#连接MongoDb

client=MongoClient('localhost',27017)

#选择或创建数据库

db=client['mongo_database']

#选择或创建集合

collection=db['mongo_collection']

3 语法

READ

#查询所有文档

collection.find()

#查询当个文档

collection.find_one()

#带条件查询

collection.find({"color":"red"})

#多条件查询(and,or,$nor)

collection.find({ "and": \[ {"age": {"gt": 25}}, {"city": "New York"} ] })

#模糊查询

collection.find("name":{"$regex":"^A"})

#结果打印

for doc in collection.find()

INSERT

#插入单条

collection.insert_one(doc)

#插入多条

collection.insert_many(docs)

UPDATE

#更新单个文档

query={"color":"red"}

newvalues={"$set":{"type":"flower"}}

collection.update_one(query,newvalues)

#更新多个文档

query={"color":"red"}

newvalues={"$set":{"type":"flower"}}

collection.update_many(query,newvalues)

DELETE

#删除单个文档

query={"color":"red"}

collection.delete_one(query)

#删除多个文档

query={"color":"green"}

collection.delete_many(query)

4.索引

#创建索引

collection.create_index([("color",pymongo.ASCENDING)])
#创建复合索引

collection.create_index([("color", pymongo.ASCENDING), ("type", pymongo.DESCENDING)])

5 聚合管道

使用聚合管道

pipeline = [

{"match": {"color": "red"}},#先用match筛选

{"group": {"_id": "type", "count": {"sum": 1}}}#再用group分组

]

6 事务

确保MongoDB在副本集模式下运行(事务需要副本集)

db = client['mydatabase']

with client.start_session() as session:

with session.start_transaction(): # 在此执行事务操作

collection1.insert_one(doc1, session=session)

collection2.insert_one(doc2, session=session)

7 线程池

创建一个连接池, 操作完成后,连接会自动返回到连接池中

client = MongoClient('localhost', 27017, maxPoolSize=100)3

8 详解多条件查询

一、多条件组合查询

  1. ‌隐式 AND 操作‌

多个条件在字典中并列时默认执行 AND 操作:

query = {

"age": {"$gt": 25}, # 年龄大于25

"city": "New York", # 城市为纽约

"status": "active" # 状态为活跃

}

results = collection.find(query) # 同时满足三个条件:ml-citation{ref="1,3" data="citationList"}

  1. ‌显式逻辑运算符‌

使用 and、or 等运算符组合条件:

AND 操作

query = {

"$and": [

{"age": {"$gte": 30}},

{"salary": {"$lt": 5000}}

]

}

OR 操作

query = {

"$or": [

{"department": "IT"},

{"department": "HR"}

]

}

results = collection.find(query) # 显式逻辑组合:ml-citation{ref="3" data="citationList"}

  1. ‌混合逻辑操作‌

嵌套使用 and 和 or:

query = {

"$and": [

{"$or": [{"role": "manager"}, {"role": "director"}]},

{"join_date": {"$gt": "2023-01-01"}}

]

}

二、嵌套字段查询

使用点记号访问嵌套字段:

query = {

"address.city": "Beijing",

"address.zip_code": {"$regex": "^10"} # 邮编以10开头

}

results = collection.find(query) # 嵌套结构查询
三、更新操作的多条件

  1. ‌更新单条文档‌ (update_one)

collection.update_one(

{"name": "Alice", "status": "pending"}, # 查询条件

{"$set": {"status": "completed"}} # 更新操作

) # 仅更新第一条匹配文档:ml-citation{ref="1,6" data="citationList"}
2. ‌批量更新‌ (update_many)

collection.update_many(

{

"department": "Finance",

"level": {"$in": [3, 4]} # 级别为3或4

},

{"$inc": {"salary": 1000}} # 薪水增加1000

) # 更新所有匹配文档:ml-citation{ref="6" data="citationList"}
collection.update_many(

{"and": \[{"department": "IT"}, {"salary": {"lt": 5000}}]}, # 同时满足两个条件

{"$inc": {"salary": 1000}} # 薪资增加1000

) #:ml-citation{ref="6,9" data="citationList"}

collection.update_many(

{"$or": [{"department": "HR"}, {"department": "Finance"}]}, # 满足任意一个条件

{"$set": {"bonus": 5000}} # 设置奖金

) #:ml-citation{ref="4,10" data="citationList"}

四、聚合框架中的多条件

在聚合管道中使用 $match 阶段:

pipeline = [

{"$match": {

"age": {"$gte": 30},

"sales": {"$gt": 10000}

}},

{"$group": {

"_id": "$department",

"avg_sales": {"avg": "sales"}

}}

]

results = collection.aggregate(pipeline) # 多条件聚合
pipeline = [

{"match": {"and": [{"age": {"gte": 30}}, {"sales": {"gt": 10000}}]}}, # 必须同时满足

{"group": {"_id": "department", "avg_sales": {"avg": "sales"}}}

] #:ml-citation{ref="9,11" data="citationList"}

pipeline = [ {"$match": {"$or": [{"status": "active"}, {"status": "pending"}]}}, # 满足其一即可 {"$count": "total"} ] #:ml-citation{ref="4,10" data="citationList"}

五、实用技巧

正则表达式查询‌

query = {"name": {"regex": "\^J", "options": "i"}} # 名字以J开头(不区分大小写)

数组条件查询‌

query = {"tags": {"$all": ["urgent", "VIP"]}} # 同时包含urgent和VIP标签

排序与限制‌

results = collection.find(query).sort("create_time", -1).limit(10) # 按时间倒序取前10条:ml-citation{ref="4" data="citationList"}
#隐式 $and ‌ 多个并列条件默认按 $and 处理(等效于逗号分隔):

{"age": {"gt": 25}, "city": "New York"} # 隐式 AND:ml-citation{ref="5" data="citationList"} {"and": [{"age": {"$gt": 25}}, {"city": "New York"}]} # 显式 AND
#嵌套

{"$and": [

{"$or": [{"role": "manager"}, {"role": "director"}]}, # 角色为 manager 或 director

{"join_year": {"$gte": 2020}} # 且入职年份 ≥2020

]} #:ml-citation{ref="5,9" data="citationList"}

#update 的修改部分(如 $set)需用逗号分隔字段,‌**不可用 and**‌:

✅ 正确写法

{"$set": {"field1": "A", "field2": "B"}}

❌ 错误写法(导致逻辑错误)

{"$set": {"field1": "A" and "field2": "B"}} #:ml-citation{ref="1,8" data="citationList"}

相关推荐
_OP_CHEN2 分钟前
【测试理论与实践】(九)Selenium 自动化测试常用函数全攻略:从元素定位到文件上传,覆盖 99% 实战场景
自动化测试·python·测试开发·selenium·测试工具·测试工程师·自动化工具
我的xiaodoujiao2 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 38--Allure 测试报告
python·学习·测试工具·pytest
Boilermaker19928 小时前
[Java 并发编程] Synchronized 锁升级
java·开发语言
沈浩(种子思维作者)8 小时前
真的能精准医疗吗?癌症能提前发现吗?
人工智能·python·网络安全·健康医疗·量子计算
MM_MS8 小时前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
꧁Q༒ོγ꧂9 小时前
LaTeX 语法入门指南
开发语言·latex
njsgcs9 小时前
ue python二次开发启动教程+ 导入fbx到指定文件夹
开发语言·python·unreal engine·ue
alonewolf_999 小时前
JDK17新特性全面解析:从语法革新到模块化革命
java·开发语言·jvm·jdk
io_T_T9 小时前
迭代器 iteration、iter 与 多线程 concurrent 交叉实践(详细)
python
古城小栈9 小时前
Rust 迭代器产出的引用层数——分水岭
开发语言·rust