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

后端 未结 4 1052
灰色年华
灰色年华 2020-12-01 08:04

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

Collection.distinct(\"fieldname\");
         


        
4条回答
  •  天涯浪人
    2020-12-01 08:26

    Improving richsilv's answer:

    function distinct(collection, field) {
      return _.uniq(collection.find({}, {
        sort: {[field]: 1}, fields: {[field]: 1}
      }).fetch().map(x => x[field]), true);
    }
    

    How to use:

    var arrResults = distinct(MyCollection, 'myfield');
    

提交回复
热议问题