英文:
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}}}
]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论