|
| 1 | +package fundamentals.builders; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +import org.bson.Document; |
| 7 | +import org.bson.conversions.Bson; |
| 8 | + |
| 9 | +import com.mongodb.client.MongoClient; |
| 10 | +import com.mongodb.client.MongoClients; |
| 11 | +import com.mongodb.client.MongoCollection; |
| 12 | +import com.mongodb.client.MongoDatabase; |
| 13 | +import com.mongodb.client.model.Aggregates; |
| 14 | +import com.mongodb.client.model.Filters; |
| 15 | +import com.mongodb.client.model.Projections; |
| 16 | +import com.mongodb.client.model.search.SearchOperator; |
| 17 | +import com.mongodb.client.model.search.SearchPath; |
| 18 | +public class AggregateSearchBuilderExample { |
| 19 | + |
| 20 | + private static final String CONNECTION_URI = "<connection URI>"; |
| 21 | + |
| 22 | + // Match aggregation |
| 23 | + private static void runMatch(MongoCollection<Document> collection) { |
| 24 | + Bson matchStage = Aggregates.match(Filters.eq("title", "Future")); |
| 25 | + Bson projection = Aggregates.project(Projections.fields(Projections.include("title", "released"))); |
| 26 | + |
| 27 | + List<Bson> aggregateStages = Arrays.asList(matchStage, projection); |
| 28 | + System.out.println("aggregateStages: " + aggregateStages); |
| 29 | + collection.aggregate( |
| 30 | + aggregateStages |
| 31 | + ).forEach(result -> System.out.println(result)); |
| 32 | + } |
| 33 | + |
| 34 | + /* |
| 35 | + * Atlas text search aggregation |
| 36 | + * Requires Atlas cluster and full text search index |
| 37 | + * See https://www.mongodb.com/docs/atlas/atlas-search/tutorial/ for more info on requirements |
| 38 | + */ |
| 39 | + private static void runAtlasTextSearch(MongoCollection<Document> collection) { |
| 40 | + // begin atlasTextSearch |
| 41 | + Bson textSearch = Aggregates.search( |
| 42 | + SearchOperator.text( |
| 43 | + SearchPath.fieldPath("title"), "Future")); |
| 44 | + // end atlasTextSearch |
| 45 | + |
| 46 | + Bson projection = Aggregates.project(Projections.fields(Projections.include("title", "released"))); |
| 47 | + |
| 48 | + List<Bson> aggregateStages = Arrays.asList(textSearch, projection); |
| 49 | + System.out.println("aggregateStages: " + aggregateStages); |
| 50 | + |
| 51 | + System.out.println("explain:\n" + collection.aggregate(aggregateStages).explain()); |
| 52 | + collection.aggregate(aggregateStages).forEach(result -> System.out.println(result)); |
| 53 | + } |
| 54 | + |
| 55 | + public static void main(String[] args) { |
| 56 | + String uri = CONNECTION_URI; |
| 57 | + |
| 58 | + try (MongoClient mongoClient = MongoClients.create(uri)) { |
| 59 | + MongoDatabase database = mongoClient.getDatabase("sample_mflix"); |
| 60 | + MongoCollection<Document> collection = database.getCollection("movies"); |
| 61 | + |
| 62 | + // runMatch(collection); |
| 63 | + runAtlasTextSearch(collection); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments