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?
You have said" I just want to basically have an 'if one with null exists take it, else take one without' by one query", how about db.collection.find().sort().limit(1) ?
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 } );