Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: how to search for only distinct field values aka a collection.distinct("fieldname") similar to Mongo's

Tags:

I'm using Meteor, and I'm trying to find only distinct (unique) values of a field. Mongodb has the command

Collection.distinct("fieldname"); 

but it's not implemented in the Meteor driver for Mongo. I've tried using the meteor-mongo-extensions package but still got an "undefined" on the client console for a client-side Collection.distinct("fieldname");

what, essentially, is a distinct looking for?

I feel like someone this is such a basic query- like for example a list of students with their teacher as a field, and then making a list of students by teachers out of that, for example...

if I can just wrap my lazy errant brain around the general concept I can probably bash something workable out.

like image 725
aaron p Avatar asked Apr 23 '14 20:04

aaron p


People also ask

How can I get distinct values from a field in MongoDB?

To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.

What does distinct do in MongoDB?

In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.

What is Meteor MongoDB?

Meteor provides a complete open source platform for building web and mobile apps in pure JavaScript. The Meteor team chose MongoDB as its datastore for its performance, scalability, and rich features for JSON. Meteor apps run using JavaScript via Node. JS on the server and JavaScript in the phone's browser.


1 Answers

You can just use underscore.js, which comes with Meteor - should be fine for the suggested use case. You might run into performance problems if you try this on a vast data set or run it repeatedly, but it should be adequate for common-or-garden usage:

var distinctEntries = _.uniq(Collection.find({}, {     sort: {myField: 1}, fields: {myField: true} }).fetch().map(function(x) {     return x.myField; }), true); 

That will return the distinct entries in myField for all documents in Collection. Apologies if the one-liner looks a bit unwieldy; the sort and fields options and the true flag are just to make it more efficient.

like image 141
richsilv Avatar answered Sep 28 '22 09:09

richsilv