Python代码实现查询
from pymongo import MongoClient
import datetime
# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
collection = db['your_collection']
# 计算最近一个月的日期
one_month_ago = datetime.datetime.now() - datetime.timedelta(days=30)
# 执行查询
result = collection.find({
'category': '特定分类',
'date': {'$gte': one_month_ago},
'comments': {'$gt': 50}
}).sort('views', -1).limit(10)
for doc in result:
print(doc)
分析查询计划优化索引策略
- 获取查询计划:在MongoDB shell中,使用
explain()
方法可以获取查询计划。例如:
db.your_collection.find({
'category': '特定分类',
'date': {'$gte': one_month_ago},
'comments': {'$gt': 50}
}).sort('views', -1).limit(10).explain('executionStats')
- 分析查询计划:
- 扫描方式:关注
executionStats.executionSuccess
是否为true
,若为false
,表示查询执行失败。查看executionStats.executionStages
中的stage
字段,例如COLLSCAN
表示全表扫描,IXSCAN
表示索引扫描。全表扫描性能较差,应尽量避免。
- 索引使用情况:
executionStats.executionStages.indexName
字段显示使用的索引名称。若显示NULL
,则表示未使用索引。
- 排序操作:
executionStats.executionStages.inputStage
中的sortPattern
显示排序依据。若排序字段未在索引中,可能导致性能问题。
- 优化索引策略:
- 复合索引:根据查询条件,创建复合索引。例如,针对上述查询,可以创建
category
、date
、comments
和views
字段的复合索引。在Python中使用create_index
方法创建:
collection.create_index([('category', 1), ('date', 1), ('comments', 1), ('views', -1)])
- **索引顺序**:复合索引中字段顺序很重要。一般将选择性高(区分度大)的字段放在前面,对于范围查询字段(如`date`)紧跟其后,排序字段放在最后。这样可以最大程度利用索引提升查询性能。