目录
一、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
五、性能优化技巧
索引使用建议:
# 创建复合索引 collection.create_index([("category", 1), ("price", -1)]) # 查看查询执行计划 print(collection.find({"category": "电子产品"}).explain())
查询优化方法:
- 使用投影限制返回字段
- 避免使用
$where
和 JavaScript 表达式 - 对大型结果集使用批量处理
- 合理设置
batch_size
分页查询优化:
# 高效分页查询 def get_products(page=1, per_page=10): skip = (page - 1) * per_page return list(collection.find() .sort("_id", 1) .skip(skip) .limit(per_page))
本教程涵盖了MongoDB从基础到高级的查询方法,所有示例均使用Python语言实现,可直接在PyCharm中运行。建议收藏本查询表作为日常开发的快速参考。