确保 $sort 将缺失值无论升序还是降序都推到底部。

huangapple go评论61阅读模式
英文:

How to ensure that $sort push missing values to the bottom regardless of ascending or descending

问题

如果我按照一个包含缺失值的列进行排序,如果排序是升序的话,缺失值将会在顶部。

如何确保无论是升序还是降序,缺失值始终被推到底部?

英文:

If I sort based on a column that has missing values, the missing values will be on top if sort is ascending.

How to ensure that missing values always get pushed to the bottom regardless of ascending or descending?

答案1

得分: 1

你可以“临时”分配一个值,将该项强制放在列表底部,然后过滤掉它:

db.foo.aggregate([
    {$addFields: {
        'val': {$ifNull: ['$val', 99999999999999]}
    }}  
    ,{$sort: {'val': 1}}
    ,{$match: {'val': {$ne: 99999999999999}}}
]);
英文:

Slightly cheeky but you can "temporarily" assign a value that will force the item to the bottom of the list, then filter it out:

db.foo.aggregate([
    {$addFields: {
        'val':{$ifNull: [ '$val', 99999999999999 ]}
    }}  
    ,{$sort: {'val':1}}
    ,{$match: {'val':{$ne:99999999999999}}}
]);

huangapple
  • 本文由 发表于 2023年5月13日 07:49:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76240505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定