We can sort the data once we get it from the database. In the following example, we will create Users collection. We will use a sort argument ({sort: {name: 1}}) for sorting the collection data by name. The number 1 is used to set the ascending order. If we want to use the descending order, we would use -1 instead.
Users = new Mongo.Collection('users'); Users.insert({ name: 'James', email: 'eee@example.com', joined: new Date(2016, 2, 23) }); Users.insert({ name: 'John', email: 'iii@example.com', joined: new Date(2016, 2, 19) }); Users.insert({ name: 'Jennifer', email: 'aaa@example.com', joined: new Date(2016, 6, 24) }); var sortByName = Users.find({}, {sort: {name: 1}}).fetch(); var sortByEmail = Users.find({}, {sort: {email: 1}}).fetch(); var sortByJoined = Users.find({}, {sort: {joined: 1}}).fetch(); console.log(sortByName); console.log(sortByEmail); console.log(sortByJoined);
We can sort the data by email the same way.
Users = new Mongo.Collection('users'); Users.insert({ name: 'James', email: 'eee@example.com', joined: new Date(2016, 2, 23) }); Users.insert({ name: 'John', email: 'iii@example.com', joined: new Date(2016, 2, 19) }); Users.insert({ name: 'Jennifer', email: 'aaa@example.com', joined: new Date(2016, 6, 24) }); var sortByEmail = Users.find({}, {sort: {email: 1}}).fetch(); console.log(sortByEmail);
Finally, we can sort it by the joining date.
Users = new Mongo.Collection('users'); Users.insert({ name: 'James', email: 'eee@example.com', joined: new Date(2016, 2, 23) }); Users.insert({ name: 'John', email: 'iii@example.com', joined: new Date(2016, 2, 19) }); Users.insert({ name: 'Jennifer', email: 'aaa@example.com', joined: new Date(2016, 6, 24) }); var sortByJoined = Users.find({}, {sort: {joined: 1}}).fetch(); console.log(sortByJoined);