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

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.lryc.cn/news/625250.html

相关文章:

  • Spring AI + MCP Client 配置与使用详解
  • SSH 登录失败(publickey)问题总结
  • Spring AI Alibaba 项目接入兼容 OpenAI API 的大模型
  • 管理本地用户和组:红帽企业 Linux 系统安全的基础
  • 日语学习-日语知识点小记-进阶-JLPT-N1阶段蓝宝书,共120语法(4):31-40语法
  • Linux 中断机制深度分析
  • 如何生成和安全保存私钥?
  • 【DDIA】第十章:解析Reduce端连接与分组技术
  • gflags框架安装与使用
  • 【SkyWalking】单节点安装
  • 数字货币钱包的类型、特点及使用场景
  • 8.18网络编程——基于UDP的TFTP文件传输客户端
  • Kafka文件存储机制
  • LeetCode100 -- Day1
  • LeetCode 每日一题 2025/8/11-2025/8/17
  • STM32学习笔记14-I2C硬件控制
  • 嵌入式 C++ 语言编程规范文档个人学习版(参考《Google C++ 编码规范中文版》)
  • 朝花夕拾(七)--------从混淆矩阵到分类报告全面解析​
  • 远程访问公司内网电脑怎么操作?3个简单通用的跨网异地连接管理计算机方法
  • 安全基础DAY6-服务器安全检测和防御技术
  • 超级云平台:重构数字生态的“超级连接器“
  • 2025年- H98-Lc206--51.N皇后(回溯)--Java版
  • Hadoop - 1:Hadoop 技术解析;Hadoop是什么;Hadoop优势;Hadoop组成;HDFS、YARN、MapReduce 三者关系
  • <数据集>遥感飞机识别数据集<目标检测>
  • Ubuntu下无法在huggingface下载指定模型的解决方法
  • FreeRTOS学习笔记(二)
  • MySQL的多版本并发控制(MVCC):
  • Windows系统上使用GIT
  • 基于JS实现的中国象棋AI系统:多模块协同决策与分析
  • 【C语言16天强化训练】从基础入门到进阶:Day 2