Meteor:如何只搜索不同的字段值,也就是类似于 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.
推荐答案
你可以只使用 underscore.js,它与 Meteor 一起提供 - 对于建议的用例应该没问题.如果您在大量数据集上尝试或重复运行它,您可能会遇到性能问题,但它应该足以满足普通或花园使用:
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.
这篇关于Meteor:如何只搜索不同的字段值,也就是类似于 Mongo 的 collection.distinct(“fieldname")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!