再见我有一个关于mongoDB索引的问题.
我有个请求
db.my_collection.find({ "$and": [ { "expires_at": { "$ne": ISODate("0001-01-01T00:00:00Z") } }, { "expires_at": { "$lte": ISODate("2024-03-29T16:00:00Z") } }, { "operation.updated_at": { "$lte": ISODate("2024-03-29T16:00:00Z") } }], "operation.status": 3, "is_in_some_state": true, "system_type": "type3", "some_status": 1 })
我的数据库里有上百万条记录.我创建了索引
operation.status_1_expires_at_1
// some other indexes for other requests
expires_at_1_operation.updated_at_1_operation.status_1_is_in_some_state_1_system_type_1_some_status_1
我希望第二个索引,即匹配的索引,将被用于请求,但当我 Select 100时,我看到101索引被采用.
第一个问题是,为什么会这样做?
如果我告诉mongo使用第二个(精确的)索引(带有100选项),我会得到30%的搜索速度.
我试图创建一些其他索引只是为了看看是否有什么变化,当我创建100索引时,我得到了更快的搜索. 第二个问题—为什么?精确指数不是更好吗?
总结
- operation.status_1_expires_at_1—1 second+请求
- expires_at_1_operation.updated_at_1_operation.status_1_is_in_some_state_1_system_type_1_some_status_1 - 100 milliseconds request
- system_type_1—70毫秒请求
做了一些聚合来显示数据的表示.
db.my_collection.aggregate([{$group:{_id:"$system_type",count:{$sum:1}}},{$sort:{count:-1}}])
{ "_id" : "type1", "count" : 637289 }
{ "_id" : "type2", "count" : 295798 }
{ "_id" : "type3", "count" : 80788 }
{ "_id" : "type4", "count" : 5 }
即使我用type1作为system_type进行搜索,我也可以看到只有100个索引被使用.为什么?
会感激你的帮助.