2017-01-23 60 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