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

相关推荐
bluebonnet2716 分钟前
【agent开发】部署LLM(一)
python·llama
HHBon1 小时前
判断用户输入昵称是否存在(Python)
linux·开发语言·python
敢敢变成了憨憨2 小时前
java操作服务器文件(把解析过的文件迁移到历史文件夹地下)
java·服务器·python
苇柠2 小时前
Java补充(Java8新特性)(和IO都很重要)
java·开发语言·windows
敲键盘的小夜猫2 小时前
Milvus向量Search查询综合案例实战(下)
数据库·python·milvus
156082072193 小时前
在QT中,利用charts库绘制FFT图形
开发语言·qt
简简单单做算法3 小时前
基于mediapipe深度学习的虚拟画板系统python源码
人工智能·python·深度学习·mediapipe·虚拟画板
小鹭同学_3 小时前
Java基础 Day27
java·开发语言
EdmundXjs4 小时前
IO Vs NIO
java·开发语言·nio
why1514 小时前
字节golang后端二面
开发语言·后端·golang