I have a collection of 15000 documents. Some documents have sr_no
with numeric values and other with absent of sr_no
.
Now i want to get entries like all documents comes first which has sr_no
with asc then all others.
I tried .find().sort({sr_no:1})
but it return all null
entries first then asc with sr_no
.
This question seems too close with duplicate. But slightly defer with numeric key.
I answered it with hack below.
By adding the boolean property hasPrice, we can specify the order. We sorted the fields that have a value first, which ensures the ones without a price (zero or null values) are sorted last.
Solution 1: In case preservation of all null values[] or null fields in the array itself is not necessary. Filter out the not null elements using $filter , the ( all null elements) array would be empty, filter that out from documents using $match then $sort on values .
This means the only way to sort case insensitive currently is to actually create a specific "lower cased" field, copying the value (lower cased of course) of the sort field in question and sorting on that instead.
I used a dirty hack for this.
MongoDB doc says that they have priorities for sorting as posted below image.
So when i sort with asc then it sort first all null (empty key consider as null) entries then sort numeric entries.
What is hack here ?
Store sr_no : ""
with empty string default.
Now it will sort first numeric values then string.
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