Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Meteor have a distinct query for collections?

Tags:

mongodb

meteor

I'd like to return distinct fields in my collection. I know these are the docs for mongo operators, but I'm not familiar enough with the query language to know if this is possible?

Meteor.publish("distinctCollection", function() {
    return Collection.find({ ... }, fields: { "myField": 1 });
});
like image 211
TimDog Avatar asked Jan 25 '13 03:01

TimDog


People also ask

How do I get distinct records 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 collection?

Collections are Meteor's way of storing persistent data. The special thing about collections in Meteor is that they can be accessed from both the server and the client, making it easy to write view logic without having to write a lot of server code.


1 Answers

Collection.find({}).distinct('myField', true);

To use, put the following in [project]/client/lib/a.js:

LocalCollection.Cursor.prototype.distinct = function (key,random) {
  var self = this;

  if (self.db_objects === null)
    self.db_objects = self._getRawObjects(true);
  if (random)
    self.db_objects = _.shuffle(self.db_objects);
  if (self.reactive)
    self._markAsReactive({ordered: true,
                          added: true,
                          removed: true,
                          changed: true,
                          moved: true});
  var res = {};
  _.each(self.db_objects,function(value){

    if(!res[value[key]]){
        res[value[key]] = value;
    }
  });
  return _.values(res);
};
like image 187
ram1 Avatar answered Sep 21 '22 23:09

ram1