Mongoose sort, ascending and $exists Mongoose sort, ascending and $exists mongoose mongoose

Mongoose sort, ascending and $exists


You can make use of aggregation here. So, you have a collection called task.

Task Table Data

| id              | track                    || --------------- | ------------------------ || someid_1        | { "nextRun" : 10 }       || someid_2        | {  }                     || someid_3        | { "nextRun" : 3 }        |

Now, as per your requirement, out put should be-

| id           | track              || ------------ | ------------------ ||  someid_3    | { "nextRun" : 3 }  ||  someid_1    | { "nextRun" : 10 } ||  someid_2    | {  }               |

Mongodb Query

db.getCollection('Task').aggregate([{    $project: {      _id: 1,      track: 1,      nextRunExists: {        $cond: [          {              $ifNull: ["$track.nextRun", false]},          1,          0        ]      }    }}, {    $sort: {        nextRunExists: -1,        track: 1    }}])