0

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
    You can't do this if you like to have it regardless of ascending or descending order. Only way to achieve it, is to generate two subsets and make a `$unionWith` afterwards. – Wernfried Domscheit May 13 '23 at 05:48

1 Answers1

1

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}}}
]);
Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33