Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,23 @@ static FacetSearchCollector facet(final SearchOperator operator, final Iterable<
.append("facets", combineToBson(facets)));
}

/**
* Returns a {@link SearchCollector} that groups results by values or ranges in the specified faceted fields and returns the count
* for each of those groups, faceting over the entire collection.
* <p>
* Unlike {@link #facet(SearchOperator, Iterable)}, this method omits the search operator, so the facets are computed
* across all documents in the collection.</p>
*
* @param facets The non-empty facet definitions.
* @return The requested {@link SearchCollector}.
* @mongodb.atlas.manual atlas-search/facet/ facet collector
*/
@Beta({Reason.CLIENT, Reason.SERVER})
static FacetSearchCollector facet(final Iterable<? extends SearchFacet> facets) {
notNull("facets", facets);
return new SearchConstructibleBsonElement("facet", new Document("facets", combineToBson(facets)));
}

/**
* Creates a {@link SearchCollector} from a {@link Bson} in situations when there is no builder method that better satisfies your needs.
* This method cannot be used to validate the syntax.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,27 @@ void facet() {
);
}

@Test
void facetWithoutOperator() {
assertAll(
() -> assertThrows(CodecConfigurationException.class, () ->
// facet names must be unique; `BsonCodec` wraps our `IllegalStateException` into `CodecConfigurationException`
SearchCollector.facet(
asList(
stringFacet("duplicateFacetName", fieldPath("stringFieldName")),
numberFacet("duplicateFacetName", fieldPath("numberFieldName"), asList(10, 20, 30))))
// we have to render into `BsonDocument` in order to trigger the lazy check
.toBsonDocument()
),
() -> assertEquals(
documentWithoutOperator()
.toBsonDocument(),
searchCollectorWithoutOperator()
.toBsonDocument()
)
);
}

private static SearchCollector docExamplePredefined() {
return SearchCollector.facet(
exists(
Expand Down Expand Up @@ -89,4 +110,28 @@ private static Document docExampleCustom() {
fieldPath("numberFieldName"),
asList(10, 20, 30))))));
}

private static SearchCollector searchCollectorWithoutOperator() {
return SearchCollector.facet(
asList(
stringFacet(
"stringFacetName",
fieldPath("stringFieldName")),
numberFacet(
"numberFacetName",
fieldPath("numberFieldName"),
asList(10, 20, 30))));
}

private static Document documentWithoutOperator() {
return new Document("facet",
new Document("facets", combineToBson(asList(
stringFacet(
"stringFacetName",
fieldPath("stringFieldName")),
numberFacet(
"numberFacetName",
fieldPath("numberFieldName"),
asList(10, 20, 30))))));
}
}