mongodbindexingmongodb-queryq

MongoDB indexing , please explain difference between 1 and -1


mongoDB document example has two fields userid and score. And while indexing in mongoDB for userid , 1 value provided and for score its -1, i.e. { userid: 1, score: -1 }. Please explain here the difference between 1 and -1 in mongoDB indexing.

I tried indexing in mongoDB to make queries faster but with less knowledge of indexing in mongoDB I am not getting expected output


Solution

  • As @deceze suggests in their comment, the basic answer to the question is mentioned in the documentation. The answer is that the value determines whether the key is ascending (1) or descending (-1). But what does this actually mean and is it important?

    Many databases use a type of B-tree data structure as the backbone for their (standard) indexes. These data structures are ordered by nature. This specific property is one of the things that make them ideal for supporting a wide range of database queries. For example, it allows them to bound a range scan (such as $lte) as it knows that there will be no more matching values later in the index once it scans to the first key that exceeds the requested maximum value. Similarly, if the definition of the index is compatible with the sort order requested by the client then the database can satisfy the sort for "free" as it scans the index.

    For single field indexes as well as sorts on a single field, the direction specified in the index definition doesn't matter. This is because indexes can be traversed in either direction. So if your index is on { timestamp: 1 } but the sort is on { timestamp: -1 }, then the database can choose to traverse the index backwards to satisfy the requested sort.

    Directionality becomes important when compound sorts are involved. If the index is defined as { score: 1, timestamp: 1 } then the database will either be less efficient or completely unable to use it to satisfy a sort on { score: 1, timestamp: -1 }. This is a direct consequence of the structure of the underlying b-tree data structure that the index is built on. More information can be found here in the documentation.

    I tried indexing in mongoDB to make queries faster but with less knowledge of indexing in mongoDB I am not getting expected output

    This is a much different and more specific question than the one that you have actually asked. If there is a particular query that you are trying to improve the performance of, then it may be beneficial to post a question with that query (and the associated .explain() output). That would allow us to advise on actionable steps to help you improve the performance of the operation (or understand why it cannot be done), as opposed to having broader discussions about index definitions which may or may not be relevant to your issue.