我有一个Meteor集合,其中有一个名为type
的字段。我想知道是否有办法选择每个type
的一个文件。例如,如果我的集合中有以下文档(按降序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。
答案 0 :(得分:3)
您可以先找到所有distinct类型
var distinctTypes = db.mycollection.distinct("type");
然后你可以循环来推送来自findOne
的所有文件,如此
var docs = [];
distinctTypes.forEach(function (thisType) {
docs.push(db.mycollection.findOne({type: thisType});
});
从这里你可以改变上面的代码,以指定每种类型的倍数时你想要哪一个。
更新:由于Meteor仍然不支持distinct
,您可以像这样使用下划线uniq
var distinctTypes = _.uniq(Collection.find({}, {
sort: {type: 1}, fields: {type: true}
}).fetch().map(function(x) {
return x.type;
}), true);
答案 1 :(得分:0)
您可以分两步完成此操作:首先,您使用$group
获取计数,type
标识,然后计算所有计数= 1的$match
。
db.fruit_collection.aggregate([
{ $match: {
createdAt: { $gt: ISODate("2015-08-01T12:00:00Z") }
}},
{ $group: {
_id: "$type",
count: { $sum: 1 }
}},
{ $match: {
count: 1
}}
]);
第一个$match
就是一个例子,所以你可以忽略。第二部分和第三部分应该给你想要的结果。