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"}

相关推荐
databook5 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar6 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780516 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_6 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机13 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
似水流年流不尽思念13 小时前
MongoDB 有哪些索引?适用场景?
后端·mongodb
数据智能老司机14 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机14 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机14 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i14 小时前
drf初步梳理
python·django