How to sort collections in Meteor

10-06-2015 (d-m-Y)

I thought it's clear how to sort collections in Meteor, but it isn't for beginners. MongoDB uses $orderby operator for sorting and Meteor uses sort operator. It might not be clear how to use sort operator in Meteor from its docs.

Let's say we have a collection named Messages:

Messages = new Mongo.Collection('messages');

The schema of the collection looks like this:

_id: String,
  text: String,
username: String,
  timestamp: Number

Then we want to publish messages with limit and sort operator/option:

Meteor.publish('messages', function(limit) {
  return Messages.find({}, {
    limit: limit || 5,
    sort: { timestamp: -1 }

sort: { timestamp: -1 } option means that we sort messages by timestamp in descendant order. If we wanted to sort messages by timestamp in ascendant order, we would use sort: { timestamp: 1 }.

Call subscribe on the client:

Meteor.subscribe('messages', 10); //subscribe 10 messages 

Write a helper that returns sorted messages. It's not enough to call Messages.find(); because it would not sort messages by timestamp:

  messages: function () {
    return Messages.find({}, {
      sort: { timestamp: -1 }

Now just show messages in a template:

<template name="messages">
  {{#each messages}}
    <p>{{username}}: {{text}}</p>

That's all. I have created a chat application which you can clone and play with it:

Learn more about using MongoDB in Meteor in this video:


← All articles | If you want to know about new blogposts you should follow @elfoslav

comments powered by Disqus