面试题答案
一键面试from pymongo import MongoClient
# 连接到MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
collection = db['your_collection']
# 创建复合索引
collection.create_index([('name', 1), ('age', -1)])
# 多条件查询
results = collection.find({
'age': {'$gt': 30},
'score': {'$gt': 80}
})
for result in results:
print(result)
这个复合索引能优化此查询的原因是:虽然查询条件未完全匹配索引顺序,但MongoDB的查询优化器在某些情况下可以部分使用复合索引。在这个例子中,索引以name
升序、age
降序构建,查询条件中的age
字段可以利用到索引中的age
部分,使得查询在满足age > 30
的条件时能够利用索引快速定位数据,从而提高查询效率。尽管score
字段未包含在索引中,但age
字段利用索引筛选数据后,后续对score
字段的筛选数据量会大大减少,整体提升了查询性能。