问题
I have a collection like below
transfer_collection
- type
- value
- from
- to
- timestamp
What I want to extract from the collection is the highest 100 values with certain type within certain time period.
For example,
db.getCollection('transfer_collection').find({$and:[{"type":"normal"}, {"timestamp":{$gte:ISODate("2018-01-10T00:00:00.000Z")}}, {"timestamp":{$lt:ISODate("2018-01-11T00:00:00.000Z")}}]}).sort({"value":-1}).limit(100)
My question is, for query performance, how to make index?
- {timestamp:1, type:1, value:-1}
- {type:1, timestamp:1, value:-1}
- {type:1, value:-1, timestamp:1}
- any other else?
Thank you in advance.
回答1:
In the query, the compound index on { type: 1, timestamp: 1, value: -1 } looks like an obvious choice. But, it is not so.
The keys in a compound index are used in a query's sort only if the query conditions before the sort have equality condition, not range conditions (using operators like $gte, $lt, etc.), as in this case where the key before sort is not an equality condition ("timestamp":{$gte:ISODate....
This requires the organization of the index as: { type: 1, value: -1, timestamp: 1 }
This is a concept called as Equality, Sort and Range; the keys of the compound index are to be in that order - the type field with equality condition, the value field with the sort operation, and the rage condition for the timestamp field.
Verify this by running the explain() function with the query. Use "executionStats" mode and check the results. The query plan should have a winningPlan with IXSCAN and there should not be a SORT stage (a sort operation that uses an index will not have the sort stage).
Note About Query Filter Document:
The query filter: { $and: [ { "type":"normal" }, {"timestamp":{ $gte:ISODate("2018-01-10T00:00:00.000Z") } }, { "timestamp": { $lt:ISODate("2018-01-11T00:00:00.000Z") } } ] }
In the query, you don't need to use the $and operator. The query filter can be written somewhat in a simpler way as follows:
find( { "type":"normal", "timestamp": { $gte:ISODate("2018-01-10T00:00:00.000Z"), $lt:ISODate("2018-01-11T00:00:00.000Z") } } ).sort(...)...
来源:https://stackoverflow.com/questions/58584973/how-to-configure-mongodb-index-for-sorting-by-value-within-time-range-with-certa