Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...