Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose sort, ascending and $exists

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.

like image 813
Mahmoud Ezzat Avatar asked May 04 '17 14:05

Mahmoud Ezzat


1 Answers

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
    }
}])
like image 151
Pankaj Tanwar Avatar answered Oct 21 '22 12:10

Pankaj Tanwar