I wonder if there is a way in mongoose that I can sort a query on a collection in ascending order on a certain field where that field also gets sorted on $exist.
I mean the following query sorts like I want but puts the documents with no track.nextRun on top of the array
db.Task.find().sort({ 'track.nextRun': 1 })
I'd like to have the documents with no track.nextRun on the bottom of the array.
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
    }
}])
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With