2017-01-23 52 views
1

我需要在find标准的集合中获得随机化的文档样本。MongoDB Java API - 如何将样本聚合与查找查询结合起来?

Bson sample = com.mongodb.client.model.Aggregates.sample(size); 
BasicDBObject query = new BasicDBObject().append("myKey", value); 

我如何可以结合本sample聚集与find查询?

+0

你的用例是什么?您不能将聚合与常规查找操作组合在一起。如果你想要样本运算符,使用聚合。 – Veeram

+0

我需要根据集合中的字段(布尔字段)来抽取一些文档。 @Veeram – talha06

回答

2

您可以使用$match$sample之间的聚合。

import static com.mongodb.client.model.Aggregates.*; 
import static com.mongodb.client.model.Filters.*; 
import static java.util.Arrays.asList; 

Bson match = match(eq("myKey", value)); 
Bson sample = sample(size); 
collection.aggregate(asList(match, sample)); 
+0

尽管'db.coll1.count({key1:false,key2:true})'返回2946个文档,'Bson sample = com.mongodb.client.model.Aggregates.sample(size); Bson match1 = com.mongodb.client.model.Aggregates.match(eq(“key1”,true)); Bson match2 = com.mongodb.client.model.Aggregates.match(eq(“key2”,false)); Bson matchFilters = and(match1,match2); mongoDB.getCollection(“coll1”)。aggregate(asList(sample,matchFilters))'只返回46个文档。这个问题的任何理由? – talha06

+1

你的样本量是多少?它会返回等于样本大小的文档,也会变成'aggregate(asList(matchFilters,sample))' – Veeram

+0

好吧,在更改聚合顺序后,现在它按预期工作。非常感谢你非常感谢你的帮助。 – talha06