面试题答案
一键面试创建索引
为了优化查询性能,可以在category
、price
和rating
字段上创建复合索引。假设使用的是MongoDB的mongo
shell,创建索引的语句如下:
db.products.createIndex({category: 1, price: 1, rating: 1});
上述语句中,1
表示升序索引,如果想使用降序索引,可以使用-1
。这个复合索引可以覆盖category
、price
和rating
相关的查询条件,有助于提高查询性能。
查询语句
完整的查询语句如下:
db.products.find({
$or: [
{category: 'electronics', price: {$gt: 500}},
{rating: {$gt: 4.5}}
]
});
该查询语句使用$or
操作符,满足category
为'electronics'且price
大于500,或者rating
大于4.5的条件。通过前面创建的复合索引,查询性能会得到提升。