汕头网站搜索优化,嘉兴网络项目建站公司,微信公号嵌入网站开发,网站开发工具怎么改内容目录
一、MongoDB3步快速安装
1.1下载安装包
1.2运行安装程序
1.3验证安装打开CMD执行#xff1a;
1.4 基本查询操作
二、高级查询操作符表
2.1 比较操作符
2.2 逻辑操作符
2.3 元素操作符
2.4 数组操作符
三、高级查询案例
3.1 复杂条件组合
3.2 数组查…目录
一、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
五、性能优化技巧 索引使用建议 # 创建复合索引
collection.create_index([(category, 1), (price, -1)])# 查看查询执行计划
print(collection.find({category: 电子产品}).explain()) 查询优化方法 使用投影限制返回字段避免使用 $where 和 JavaScript 表达式对大型结果集使用批量处理合理设置 batch_size 分页查询优化 # 高效分页查询
def get_products(page1, per_page10):skip (page - 1) * per_pagereturn list(collection.find().sort(_id, 1).skip(skip).limit(per_page))
本教程涵盖了MongoDB从基础到高级的查询方法所有示例均使用Python语言实现可直接在PyCharm中运行。建议收藏本查询表作为日常开发的快速参考。