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

I am using this query in mongo shell

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

      

result

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 a 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

      

In different ways, "the zero in the last list is ordered in the list. How can I do this?

+3


source to share


1 answer


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); });

      

+4


source







All Articles