F
F
fatalispm2014-04-13 21:37:00
NoSQL
fatalispm, 2014-04-13 21:37:00

What is the correct way to use indexes in MongoDB?

Recently, I became interested in MongoDB and sat down to read what it is for the weekend, and faced the fact that I don’t quite understand how indexes are arranged in Mongo
. The query is parsed:

db.users.find({"age" : {"$gte" : 25, "$lte" : 35}}).
sort({"username" : 1}).limit(100)
and it is advised to take the following index {"username" : 1, "age" : 1}, instead of
{"age":1,"username":1}.
If the number of records in the database is N(N>=10^6), and the number of suitable records is K(K=N/10), then in the first case the number of reads from external memory (in the worst case) will be O(N), and in the second is K+time to sort K elements ~O(K*log(K)), which seems to be much faster in N reads from external memory. Correct me if wrong anywhere.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2014-04-16
@lega

db.users.find({"age" : {"$gte" : 25, "$lte" : 35}}).sort({"username" : 1}).limit(100)
it is advised to take the following index {" username" : 1, "age" : 1}, instead of
{"age":1,"username":1}.

And it should be the other way around.
Often (but not always) the order is:
1) Filter for exact values
​​2) Sort fields
3) Filter for "sample" values ​​(arrays).
In your case ("age" : {"$gte" : 25, "$lte" : 35}) is sort of the exact value (because it fits into "a < x < b"), then sorting ("username" : 1).
Those. it turns out that the monga "takes" a data packet ...24,|25<=age<=35|,36... where in each of the ages it selects all the values ​​in order. they are already sorted.
If the index is the opposite ({"username" : 1, "age" : 1}), then the monga will "enter" as if into each username, take the range 25<=age<=35 from each occurrence, and then sort all the data. - i.e. sorting at the beginning is superfluous here.
Something like this.
It is very important that the sorting "does not break" when passing through the index.
Here is a useful article.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question