从集合中选择每种类型之一 [英] Select one of each type from collection
问题描述
我有一个 Meteor 集合,它有一个名为 type
的字段.我想知道是否有办法选择每个 type
的一个文档.例如,如果我的集合中有以下文档(按降序排序 createdAt
)
I have a Meteor collection that has a field called type
. I'm wondering if there's a way to select one document of each type
. For example, if I had the following documents in my collection (sorted by descending createdAt
)
Document #1: {type = "apple", createdAt: ...}
Document #2: {type = "apple", createdAt: ...}
Document #3: {type = "grape", createdAt: ...}
Document #4: {type = "orange", createdAt: ...}
Document #5: {type = "orange", createdAt: ...}
Document #6: {type = "grape", createdAt: ...}
Document #7: {type = "apple", createdAt: ...}
...
那我怎么能选择 3 个文档,每个文档都具有唯一类型?在这个例子中,我需要文档 #1、#3 和 #4.
Then how could I select 3 documents each with a unique type? In this example, I would need Document #1, #3, and #4.
推荐答案
你可以先找到所有的 不同的类型与
You could first find all the distinct types with
var distinctTypes = db.mycollection.distinct("type");
然后你可以像这样循环从 findOne
推送所有文档
and then you can loop through to push all the documents from findOne
like so
var docs = [];
distinctTypes.forEach(function (thisType) {
docs.push(db.mycollection.findOne({type: thisType});
});
从这里你可以改变上面的代码,如果每种类型有多个,你可以指定你想要哪个.
From here you can alter the above code to specify which one you want if there are multiples of each type.
更新:由于 Meteor 仍然不支持 distinct
,您可以像这样使用下划线 uniq
UPDATE: Since Meteor still doesn't support distinct
, you can use the underscore uniq
like so
var distinctTypes = _.uniq(Collection.find({}, {
sort: {type: 1}, fields: {type: true}
}).fetch().map(function(x) {
return x.type;
}), true);
这篇关于从集合中选择每种类型之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!