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

相关推荐
心平气和量大福大9 分钟前
C#-WPF-Window主窗体
开发语言·c#·wpf
从零开始的代码生活_1 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸2 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
C^h2 小时前
python函数学习
人工智能·python·机器学习
Fanta丶2 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python
决战灬2 小时前
langgraph之interrupt(理论篇)
人工智能·python·agent
GIS阵地2 小时前
QgsSingleBandPseudoColorRenderer 完整详解(QGIS 3.40.13 C++)
开发语言·前端·c++·qt·qgis
兜客互动2 小时前
2026年AI关键词拓展挖掘软件,高效助力内容创作精准获流
人工智能·python
weixin_538601972 小时前
智能体测开Day30pytest测试框架
python
MC皮蛋侠客2 小时前
uv 系列(七):CI/CD、Docker 与私有索引——生产级交付
python·ci/cd·docker·uv