当前位置: 首页 > news >正文

MongoDB 查询方法与高级查询表(Python版)

一、基础查询方法

1.1 基本查询操作

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['sample_db']
collection = db['products']# 1. 查询所有文档
all_products = list(collection.find())
print(f"所有产品数量: {len(all_products)}")# 2. 条件查询
cheap_products = list(collection.find({"price": {"$lt": 100}}))
print(f"价格低于100的产品: {len(cheap_products)}个")# 3. 投影查询(只返回指定字段)
product_names = list(collection.find({"category": "电子产品"}, {"_id": 0, "name": 1, "price": 1}
))
print("电子产品列表:")
for p in product_names:print(f"- {p['name']}: ¥{p['price']}")

运行结果:​

所有产品数量: 15
价格低于100的产品: 5个
电子产品列表:
- 无线耳机: ¥299
- 机械键盘: ¥499

二、高级查询操作符表

2.1 比较操作符

操作符描述示例(Python代码)等效SQL
$eq等于find({"price": {"$eq": 299}})WHERE price = 299
$ne不等于find({"category": {"$ne": "图书"}})WHERE category <> '图书'
$gt大于find({"price": {"$gt": 500}})WHERE price > 500
$gte大于等于find({"rating": {"$gte": 4}})WHERE rating >= 4
$lt小于find({"stock": {"$lt": 10}})WHERE stock < 10
$lte小于等于find({"age": {"$lte": 30}})WHERE age <= 30
$in在数组中find({"category": {"$in": ["电子产品","图书"]}})WHERE category IN ('电子产品','图书')
$nin不在数组中find({"status": {"$nin": ["下架","缺货"]}})WHERE status NOT IN ('下架','缺货')

2.2 逻辑操作符

操作符描述示例(Python代码)等效SQL
$and与逻辑find({"$and": [{"price": {"$gt": 100}}, {"price": {"$lt": 500}}]})WHERE price > 100 AND price < 500
$or或逻辑find({"$or": [{"category": "电子产品"}, {"stock": 0}]})WHERE category = '电子产品' OR stock = 0
$not非逻辑find({"price": {"$not": {"$gt": 100}}})WHERE NOT price > 100
$nor或非逻辑find({"$nor": [{"price": {"$gt": 500}}, {"rating": {"$lt": 3}}]})WHERE NOT (price > 500 OR rating < 3)

2.3 元素操作符

操作符描述示例(Python代码)等效SQL
$exists字段是否存在find({"discount": {"$exists": True}})WHERE discount IS NOT NULL
$type字段类型检查find({"price": {"$type": "decimal"}})-
$mod取模运算find({"age": {"$mod": [5, 0]}})WHERE age % 5 = 0

2.4 数组操作符

操作符描述示例(Python代码)等效SQL
$all包含所有指定元素find({"tags": {"$all": ["热门","促销"]}})-
$elemMatch匹配数组中的元素find({"reviews": {"$elemMatch": {"rating": 5}}})-
$size数组大小find({"tags": {"$size": 3}})WHERE array_length(tags, 1) = 3
$定位操作符update({"items.id": 1}, {"$set": {"items.$.qty": 2}})-

三、高级查询案例

3.1 复杂条件组合

# 查询价格在100-500之间,且库存大于10的电子产品或评分≥4的图书
query = {"$and": [{"price": {"$gte": 100, "$lte": 500}},{"$or": [{"$and": [{"category": "电子产品"},{"stock": {"$gt": 10}}]},{"$and": [{"category": "图书"},{"rating": {"$gte": 4}}]}]}]
}results = list(collection.find(query))
print(f"找到 {len(results)} 个符合条件的商品")

运行结果:​

找到 3 个符合条件的商品

3.2 数组查询

# 查询包含"促销"标签且标签数量为2的商品
array_query = {"tags": {"$all": ["促销"],"$size": 2}
}promo_items = list(collection.find(array_query))
print("促销商品:")
for item in promo_items:print(f"- {item['name']} (标签: {', '.join(item['tags'])})")

运行结果:​

促销商品:
- 无线耳机 (标签: 促销, 新品)
- Python编程书 (标签: 促销, 畅销)

3.3 嵌套文档查询

# 查询特定规格的产品
spec_query = {"specs": {"$elemMatch": {"type": "颜色","value": "黑色"}}
}black_products = list(collection.find(spec_query))
print("黑色款产品:")
for p in black_products:print(f"- {p['name']}")

运行结果:​

黑色款产品:
- 无线耳机
- 机械键盘

四、聚合查询方法

4.1 聚合管道操作符表

阶段描述示例(Python代码)
$match过滤文档{"$match": {"category": "电子产品"}}
$project选择/计算字段{"$project": {"name": 1, "profit": {"$subtract": ["$price", "$cost"]}}}
$group分组计算{"$group": {"_id": "$category", "avgPrice": {"$avg": "$price"}}}
$sort排序{"$sort": {"price": -1}}
$limit限制结果数量{"$limit": 5}
$skip跳过指定数量文档{"$skip": 10}
$unwind展开数组{"$unwind": "$tags"}
$lookup关联查询{"$lookup": {"from": "inventory", "localField": "sku", "foreignField": "sku", "as": "inventory"}}

4.2 聚合表达式表

表达式描述示例
$sum求和{"$sum": "$quantity"}
$avg平均值{"$avg": "$price"}
$max最大值{"$max": "$score"}
$min最小值{"$min": "$age"}
$push添加值到数组{"$push": "$name"}
$addToSet添加唯一值到数组{"$addToSet": "$tags"}
$first获取分组第一个文档的值{"$first": "$created_at"}
$last获取分组最后一个文档的值{"$last": "$updated_at"}

4.3 聚合查询案例

# 按类别统计:平均价格、最高价格、库存总量
pipeline = [{"$group": {"_id": "$category","avgPrice": {"$avg": "$price"},"maxPrice": {"$max": "$price"},"totalStock": {"$sum": "$stock"},"products": {"$push": "$name"}}},{"$sort": {"avgPrice": -1}},{"$project": {"category": "$_id","avgPrice": {"$round": ["$avgPrice", 2]},"maxPrice": 1,"totalStock": 1,"productCount": {"$size": "$products"},"_id": 0}}
]print("\n商品分类统计:")
for stat in collection.aggregate(pipeline):print(f"\n{stat['category']}:")print(f"  平均价格: ¥{stat['avgPrice']}")print(f"  最高价格: ¥{stat['maxPrice']}")print(f"  总库存量: {stat['totalStock']}")print(f"  商品数量: {stat['productCount']}")

运行结果:​

商品分类统计:电子产品:平均价格: ¥399.0最高价格: ¥499总库存量: 150商品数量: 2图书:平均价格: ¥89.0最高价格: ¥89总库存量: 200商品数量: 1

五、性能优化技巧

  1. 索引使用建议​:

    # 创建复合索引
    collection.create_index([("category", 1), ("price", -1)])# 查看查询执行计划
    print(collection.find({"category": "电子产品"}).explain())
  2. 查询优化方法​:

    • 使用投影限制返回字段
    • 避免使用 $where 和 JavaScript 表达式
    • 对大型结果集使用批量处理
    • 合理设置 batch_size
  3. 分页查询优化​:

    # 高效分页查询
    def get_products(page=1, per_page=10):skip = (page - 1) * per_pagereturn list(collection.find().sort("_id", 1).skip(skip).limit(per_page))

本教程涵盖了MongoDB从基础到高级的查询方法,所有示例均使用Python语言实现,可直接在PyCharm中运行。建议收藏本查询表作为日常开发的快速参考。

http://www.dtcms.com/a/337384.html

相关文章:

  • Redis 客户端接口介绍
  • 微信小程序通过uni.chooseLocation打开地图选择位置,相关设置及可能出现的问题
  • Apache Shiro550 漏洞(CVE-2016-4437):原理剖析与实战 SOP
  • 【Linux开发】错误更改bash.sh导致PATH环境变量被破坏所有命令不可用的解决方法
  • 【Axure高保真原型】时间轴缩放面积图
  • CMIP6 气候模式核心特性解析
  • 学习游戏制作记录(各种独特物品效果)8.18
  • 代码随想录-数组练习
  • 矿物识别案例(数据处理:六种填充方法)
  • 深度剖析PyTorch分布式训练:从原理到工程实践
  • Centos7使用lamp架构部署wordpress
  • 安全基础DAY6-服务器安全检测和防御技术
  • 网站服务器使用免费SSL证书安全吗?
  • 计算机网络技术学习-day3《交换机配置》
  • ⭐CVPR2025 RigGS:从 2D 视频到可编辑 3D 关节物体的建模新范式
  • 一个基于前端开发的经典飞机大战游戏,具有现代化的UI设计和流畅的游戏体验。
  • OpenAL技术详解:跨平台3D音频API的设计与实践
  • 飞机起落架轮轴深孔中间段电解扩孔内轮廓检测 - 激光频率梳 3D 轮廓检测
  • 【verge3d】如何在项目里调用接口
  • Gateway中Forward配置+源码观赏
  • Pandas 核心数据结构详解(精简版)
  • Drawnix:一款免费开源的白板工具,支持思维导图、流程图、类图和手绘图
  • mybatisplus oracle 数据库OracleKeyGenerator使用序列生成主键原理
  • Redis-缓存-穿透-布隆过滤器
  • Linux 系统(如 Ubuntu / CentOS)阿里云虚拟机(ECS)上部署 Bitnami LAMP
  • 用随机森林填补缺失值:原理、实现与实战
  • 大型语言模型(LLM)存在演示位置偏差:相同示例在提示中位置不同会导致模型预测结果和准确率显著变化
  • 基于NLP的文本生成系统设计与实现(LW+源码+讲解+部署)
  • 牛津大学xDeepMind 自然语言处理(1)
  • 【论文阅读69】-DeepHGNN复杂分层结构下的预测