MongoDB sort by only exists entry, key with value first and key with null or not exists last

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

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.

回答1:

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!