MongoDB排序依据仅存在条目,键的值优先于键,键的值为空或不存在,最后不存在

问题描述:

我收藏了15000个文档.某些文档具有带有数字值的 sr_no ,而其他文档则缺少 sr_no .

I have a collection of 15000 documents. Some documents have sr_no with numeric values and other with absent of sr_no.

现在,我想获取所有文档一样的条目,第一个包含 sr_no asc ,然后是其他所有文档.

Now i want to get entries like all documents comes first which has sr_no with asc then all others.

我尝试了 .find().sort({sr_no:1}) ,但是它先返回所有 null 条目,然后返回 asc sr_no >.

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.

我在下面用hack回答了它.

我为此使用了肮脏的技巧.

I used a dirty hack for this.

MongoDB doc 说,他们排序优先,如下图所示.

MongoDB doc says that they have priorities for sorting as posted below image.

因此,当我使用 asc 进行排序时,它将首先对所有 null (空键视为null)条目进行排序,然后对数字条目进行排序.

So when i sort with asc then it sort first all null (empty key consider as null) entries then sort numeric entries.

这是什么黑客?

使用空字符串默认存储sr_no : "".

Store sr_no : "" with empty string default.

现在,它将首先对数字值进行排序,然后对 string 进行排序.

Now it will sort first numeric values then string.