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

前端 未结 2 418
日久生厌
日久生厌 2020-11-30 13:05

I excute this query in the mongo shell

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

the result is

next_time
-         


        
2条回答
  •  无人及你
    2020-11-30 13:25

    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.

提交回复
热议问题