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

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

目录

一、MongoDB3步快速安装

1.1​下载安装包

1.2运行安装程序​

1.3​验证安装​打开CMD执行:

1.4 基本查询操作

二、高级查询操作符表

2.1 比较操作符

2.2 逻辑操作符

2.3 元素操作符

2.4 数组操作符

三、高级查询案例

3.1 复杂条件组合

3.2 数组查询

3.3 嵌套文档查询

四、聚合查询方法

4.1 聚合管道操作符表

4.2 聚合表达式表

4.3 聚合查询案例

五、性能优化技巧


一、MongoDB3步快速安装

1.1​下载安装包


访问官网下载社区版:https://www.mongodb.com/try/download/community
选择:Windows系统 → .msi格式 → 最新稳定版

1.2运行安装程序
  • 双击下载的.msi文件
  • 选择"Complete"完整安装
  • 勾选"Install MongoDB as a Service"(默认数据目录:C:\data\db
  • 安装图形工具Compass(推荐勾选)
1.3​验证安装
打开CMD执行:
mongod --version  # 查看版本
mongo            # 连接数据库
1.4 基本查询操作
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.xdnf.cn/news/18329.html

相关文章:

  • 计算机网络技术学习-day3《交换机配置》
  • steal tsoding‘s pastebeam code as go server
  • SQL详细语法教程(五)事务和视图
  • ubuntu 下载安装tomcat简单配置(傻瓜式教程)
  • 如何生成和安全保存私钥?
  • 信号上升时间Tr不为0的信号反射情况
  • scikit-learn/sklearn学习|弹性网络ElasticNet解读
  • linux系统查看ip命令
  • 深度学习与线性模型在扰动预测上的比较
  • kafka 冲突解决 kafka安装
  • 如何在VS Code中使用Copilot与MCP服务器增强开发体验
  • 【Linux操作系统】简学深悟启示录:进程状态优先级
  • Android RxBinding 使用指南:响应式UI编程利器
  • 数据转换细节揭秘:ETL如何精准映射复杂业务逻辑
  • 27.Linux 使用yum安装lamp,部署wordpress
  • 【自动化测试】Selenium详解-WebUI自动化测试
  • Linux: RAID(磁盘冗余阵列)配置全指南
  • 作业标准化:制造企业的效率基石与品质保障
  • 可编辑150页PPT | 某制造集团产业数字化转型规划方案
  • idea部署到docker
  • 【MyBatis-Plus】一、快速入门
  • kafka 发送消息有哪些模式?各自的应用场景是什么?
  • 秋招笔记-8.17
  • Java 学习笔记(基础篇5)
  • 【OpenAI】 GPT-4o-realtime-preview 多模态、实时交互模型介绍+API的使用教程!
  • 宋红康 JVM 笔记 Day05|运行时数据区内部结构、JVM中的线程说明、程序计数器
  • RAID服务器
  • PDF处理控件Aspose.PDF教程:将 PNG 合并为 PDF
  • HTTP协议-4-浏览器是怎么抉择HTTP版本的?
  • 【Java基础】反射,注解,异常,Java8新特性,object类-详细介绍