2

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!

1
  • can you give one or two sample documents, and the expected result? Commented Sep 30, 2021 at 20:38

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This works, but I ended up using slightly different code. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.