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?
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? 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 −
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.
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.
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 } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With