o9np9q
Last Updated: February 25, 2016
·
9.723K
· pent

Get unique values from a collection in Meteor

Since Meteor doesn't support distinct in MongoDB (yet), I had to find a way to get distinct values myself. We do this with the wonderful underscore.js library.

  • To use this you must first convert the Meteor cursor returned by .find() to an array by using .fetch() on your cursor. Example:
var myArray = CollectionName.find().fetch();
  • Once we have a usable array, use the uniq function in underscore to return a bunch of unique arrays. You use the callback function to determine which unique value to seek. Note: this returns the full array, not just the value specified in the callback. We set sort to false in this instance.
var distinctArray = _.uniq(myArray, false, function(d) {return d.foo});
  • Then you can use the pluck function to just return an array of the unique values
var disctinctValues = _.pluck(distinctArray, 'foo');

Woolah, I hope this helps someone out there.

3 Responses
Add your response

8091

nICE,
thanks so much for this! Saved me bro

over 1 year ago ·
16385

thanks! saved me a bit of time. maybe meteor supports this natively now tho, at least on the server?

over 1 year ago ·
17910

Great, I was looking for this a looong time :)

over 1 year ago ·