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

后端 未结 4 1037
灰色年华
灰色年华 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:34

    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.

提交回复
热议问题