Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are null values in a MongoDB index sorted?

Tags:

mongodb

I want to sort my index in a specific way (-1, 1) and want to make sure that null values are at the top of the index. How can I ensure this?

like image 476
user1680104 Avatar asked Mar 07 '13 09:03

user1680104


People also ask

How to use index to sort query results in MongoDB?

If the sort keys correspond to the index keys or an index prefix , MongoDB can use the index to sort the query results. A prefix of a compound index is a subset that consists of one or more keys at the start of the index key pattern. For example, create a compound index on the data collection:

Is MongoDB able to index a null value?

Is MongoDB able to index a null value? Yes, MongoDB can easily index a null value. Let us first create a collection with documents − Display all documents from a collection with the help of find () method −

How to implement orderby in MongoDB with NULL values?

If there are null values also, then implement ORDERBY using sort (). Note − Since, starting in MongoDB v3.2, the $ orderby operator deprecated in the mongo shell. Use cursor.sort () instead.

Why is my sparse index not working in MongoDB?

If a sparse index would result in an incomplete result set for queries and sort operations, MongoDB will not use that index unless a hint () explicitly specifies the index. For example, the query { x: { $exists: false } } will not use a sparse index on the x field unless explicitly hinted.


1 Answers

If you are sorting descending and you are seeing null values at the end, that would be the default behaviour of the sort.

There's really not much that can be done to change that behaviour, but a workaround that will give you the results you're looking for is to do two queries instead of one:

db.Collection.find( { a: null } );
db.Collection.find( { a: { $ne: null } } ).sort( { a: -1, b: 1 } );
like image 114
Zaid Masud Avatar answered Sep 27 '22 21:09

Zaid Masud