How can I sort into that nulls are last ordered in mongodb?

I excute this query in the mongo shell

db.getCollection('list').find({}).sort({next_time: 1})

the result is

next_time
--
null
null
null
2015-02-21 00:00:00
2015-03-25 00:00:00
2015-08-29 00:00:00

I hope to make the result like this

next_time
--
2015-02-21 01:00:00
2015-03-25 01:00:00
2015-08-29 01:00:00
null
null
null

The different is that 'null's are last ordered in the list. How can I do for this?


Perhaps you can use aggregation and an artificially high end date:

c = db.foo.aggregate([
{$project: {
            next_time: 1,
            nlt: { $ifNull: [ "$next_time", new ISODate("9000-01-01") ] }
  }     
}
,
{$sort: { "nlt": 1}}
                  ]);
c.forEach(function(r) { printjson(r); });

Alternatively, if the majority of the material has nulls and you don't want to deal with those docs at all, then filter them out and just $sort the remainder:

db.foo.aggregate([
{$match: {"nt": {$exists: true}}}
,
{$sort: { "nt": 1}}
                 ]);

If you can add fields to your documents, you could add an "inverted" field that, when you sort it in descending order, would return your documents in ascending order.

Just to clarify: mongo considers null values as the "smallest" ones, so they appear first when sorting in ascending order, and appear last when sorting in descending order.

So, if your elements are like this:

{
  ...
  next_time: ISODate("2020-05-01")
}

Since ISODate("2020-05-01").getTime() is 1588291200000, you may add:

{
  ...
  next_time: ISODate("2020-05-01"),
  next_time_inverted: -1588291200000
}

And then sort the inverted value in descending order:

db.getCollection('list').find({}).sort({next_time_inverted: -1})

Don't forget to add an index on that field when necessary.