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.
Written by Jonathan Pidgeon
Related protips
3 Responses
nICE,
thanks so much for this! Saved me bro
over 1 year ago
·
thanks! saved me a bit of time. maybe meteor supports this natively now tho, at least on the server?
over 1 year ago
·
Great, I was looking for this a looong time :)
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Underscore
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#