Added $sample helper to the Aggregates builder · pkdevbox/mongo-java-driver@0023356 · GitHub
Skip to content

Commit 0023356

Browse files
committed
Added $sample helper to the Aggregates builder
JAVA-1937
1 parent 8bd220e commit 0023356

4 files changed

Lines changed: 35 additions & 0 deletions

File tree

docs/reference/content/builders/aggregation.md

Lines changed: 8 additions & 0 deletions

driver-core/src/main/com/mongodb/client/model/Aggregates.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,19 @@ public static Bson out(final String collectionName) {
165165
return new BsonDocument("$out", new BsonString(collectionName));
166166
}
167167

168+
/**
169+
* Creates a $sample pipeline stage with the specified sample size
170+
*
171+
* @param size the sample size
172+
* @return the $sample pipeline stage
173+
* @mongodb.driver.manual reference/operator/aggregation/sample/ $sample
174+
* @mongodb.server.release 3.2
175+
* @since 3.2
176+
*/
177+
public static Bson sample(final int size) {
178+
return new BsonDocument("$sample", new BsonDocument("size", new BsonInt32(size)));
179+
}
180+
168181
private static class SimplePipelineStage implements Bson {
169182
private final String name;
170183
private final Bson value;

driver-core/src/test/functional/com/mongodb/client/model/AggregatesFunctionalSpecification.groovy

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import static com.mongodb.client.model.Aggregates.limit
3636
import static com.mongodb.client.model.Aggregates.match
3737
import static com.mongodb.client.model.Aggregates.out
3838
import static com.mongodb.client.model.Aggregates.project
39+
import static com.mongodb.client.model.Aggregates.sample
3940
import static com.mongodb.client.model.Aggregates.skip
4041
import static com.mongodb.client.model.Aggregates.sort
4142
import static com.mongodb.client.model.Aggregates.unwind
@@ -46,6 +47,7 @@ import static com.mongodb.client.model.Projections.fields
4647
import static com.mongodb.client.model.Projections.include
4748
import static com.mongodb.client.model.Sorts.descending
4849
import static java.util.Arrays.asList
50+
import static org.spockframework.util.CollectionUtil.containsAny
4951

5052
class AggregatesFunctionalSpecification extends OperationFunctionalSpecification {
5153

@@ -162,4 +164,10 @@ class AggregatesFunctionalSpecification extends OperationFunctionalSpecification
162164
results.get('stdDevSamp') == 1.0
163165
}
164166

167+
@IgnoreIf({ !serverVersionAtLeast(asList(3, 1, 8)) })
168+
def '$sample'() {
169+
expect:
170+
containsAny([a, b, c], aggregate([sample(1)]).first())
171+
}
172+
165173
}

driver-core/src/test/unit/com/mongodb/client/model/AggregatesSpecification.groovy

Lines changed: 6 additions & 0 deletions

0 commit comments

Comments
 (0)