Mongo results : sort after sorting

Hey guys,

I can’t figure out how to sort my results after sorting if that makes sense?

I’m getting the latest 30 records from the collection sorted by postedAt like this :

chat: Chat.find({}, {sort: {postedAt: -1}, limit: 30}).fetch()

Which outputs like this :

post five
post four
post three
post two
post one

But I need it to output with the latest document at the bottom like this :

post one
post two
post three
post four
post five

I’ve tried a bunch of different things including $natural and reverse but I just get errors.

I understand that I am flipping the order with my sort command, but I need to do that to only show the last 30 records, so how do I then re-sort the sort?

You could do it like this

chat: Chat.find({}, {sort: {postedAt: -1}, limit: 30}).fetch().sort((a, b) => {
  if (a.postedAt > b.postedAt) return 1;
  if (a.postedAt < b.postedAt) return -1;
  return 0;

You may be able to simplify that depending on the data type of your postedAt field.

Edit: Just fixed a typo in that!

I should have mentioned that my code above is running withTracker in my export default of the ChatList component:

export default withTracker(() => {
  Meteor.subscribe('chat', 30);

  return {
    chat: Chat.find({}, {sort: {postedAt: -1}, limit: 30}).fetch()

}) (ChatList);

And this is what it looks like in main.js (server) :

Meteor.publish('chat', function (LIMIT) {
    return Chat.find({}, {sort: {postedAt: -1}, limit: LIMIT});

So I don’t think I can run functions in the component return statement can I?

Yes. That will be okay. If you can use fetch, you can add sort :slight_smile:

Note I fixed a typo in my answer!

1 Like

Thank you, that worked perfectly!

@robfallows Sorry to be a pain, but could you please explain what that extra sort function is doing now so I can understand it?

My guess is it’s cycling through every document and comparing the dates using greater than and less than operators, but I just want to be sure as that seems like quite a lot of work it’s having to do there for what essentially is a pretty straight forward sort.

Ahh so .sort is a javascript method and not a Mongo method?

That makes sense, but isn’t Mongo capable of doing this kind of thing itself?

You’ve already did a sort in MongoDB. If you badly need to do the 2nd sort using Mongodb, then check aggregate function and create a pipeline. But that makes it more complex than necessary.

Also read about method chaining in JavaScript


Here’s an alternative, which may be faster. Given that your array from fetch() is just reverse ordered, you can use the array prototype reverse() to get the ordering how you want:

Chat.find({}, {sort: {postedAt: -1}, limit: 30}).fetch().reverse();

Obviously, sort() is “safer” if your result may be unordered.