流星:如何仅搜索与Mongo类似的collection.distinct("fieldname")的不同字段值 [英] Meteor: how to search for only distinct field values aka a collection.distinct("fieldname") similar to Mongo's
问题描述
我正在使用Meteor,并且试图查找字段的唯一(唯一)值. Mongodb具有命令
I'm using Meteor, and I'm trying to find only distinct (unique) values of a field. Mongodb has the command
Collection.distinct("fieldname");
,但是在Mongo的Meteor驱动程序中未实现.
我已经尝试过使用meteor-mongo-extensions包,但是在客户端控制台上对于客户端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.
推荐答案
您可以只使用Meteor随附的underscore.js-对于建议的用例应该没问题.如果您在庞大的数据集上尝试或重复运行它,可能会遇到性能问题,但是对于普通或园艺用途而言,它应该足够了:
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);
这将为Collection
中的所有文档返回myField
中的不同条目.如果单线看上去有点笨拙,则表示歉意; sort
和fields
选项以及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.
这篇关于流星:如何仅搜索与Mongo类似的collection.distinct("fieldname")的不同字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!