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

后端 未结 4 1022
灰色年华
灰色年华 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');
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 08:35

    If you'd prefer to do this on the server and thus save client memory and bandwidth try this aggregator package. It wraps mongodb's "distinct" function. https://github.com/zvictor/meteor-mongo-server/

    0 讨论(0)
  • 2020-12-01 08:46

    A Non-Underscore, pure mongo solution would be to access the raw collection directly. This involves a Promise (though you can use await to await the resolved value).

    Note: it will run on the MongoDB server and return distinct values to the client.

    Collection._collection.rawCollection().distinct('fieldname').then(distinctValues => console.log(distinctValues)) 
    
    0 讨论(0)
提交回复
热议问题