Home > front end >  MongoDB aggregation $sort
MongoDB aggregation $sort

Time:10-02

So I am aggregating some events, and they have a field startTime. I need to sort those events by the number in that field low to high, but some of the events have 0. And I need to put those with a 0 after those with any numbers. So it would look like this: DB data: [0, 0, 0, 0, 5, 10, 20] and a wanted result is this: [5, 10, 20, 0, 0, 0, 0]

Of course the structure is a bit more complex but this should deliver the point. This is what it looks like now:

sortBy = { "el.endingSoon": 1 };

Thank you!

CodePudding user response:

There is no "custom" sort function in Mongo, what you can do is create a temporary field and sort by that, like so:

db.collection.aggregate([
  {
    $addFields: {
      tmpField: {
        $cond: [
          {
            $eq: [
              0,
              "$startTime"
            ]
          }, 
          1000000000,// largest possible value.
          "$startTime"
        ]
      }
    }
  },
  {
    $sort: {
      tmpField: 1
    }
  },
  {
    $project: {
      tmpField: 0
    }
  }
])

Mongo Playground

  • Related