|
| 1 | +package org.example; |
| 2 | +import com.mongodb.*; |
| 3 | +import com.mongodb.client.model.Projections; |
| 4 | +import com.mongodb.reactivestreams.client.*; |
| 5 | +import org.bson.Document; |
| 6 | + |
| 7 | +import reactor.core.publisher.Mono; |
| 8 | +import java.util.List; |
| 9 | +import org.bson.conversions.Bson; |
| 10 | + |
| 11 | +import com.mongodb.client.model.Aggregates; |
| 12 | +import com.mongodb.client.model.search.SearchOperator; |
| 13 | +import static com.mongodb.client.model.search.SearchPath.fieldPath; |
| 14 | +import org.reactivestreams.Publisher; |
| 15 | + |
| 16 | +public class Main { |
| 17 | + public static void main(String[] args) { |
| 18 | + // Replace the placeholder with your Atlas connection string |
| 19 | + String uri = "mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority&appName=Cluster0"; |
| 20 | + |
| 21 | + // Construct a ServerApi instance using the ServerApi.builder() method |
| 22 | + ServerApi serverApi = ServerApi.builder() |
| 23 | + .version(ServerApiVersion.V1) |
| 24 | + .build(); |
| 25 | + |
| 26 | + MongoClientSettings settings = MongoClientSettings.builder() |
| 27 | + .applyConnectionString(new ConnectionString(uri)) |
| 28 | + .serverApi(serverApi) |
| 29 | + .build(); |
| 30 | + |
| 31 | + // Create a new client and connect to the server |
| 32 | + try (MongoClient mongoClient = MongoClients.create(settings)) { |
| 33 | + MongoDatabase database = mongoClient.getDatabase("sample_mflix"); |
| 34 | + MongoCollection<Document> movies = database.getCollection("movies"); |
| 35 | + |
| 36 | + // start atlasHelperMethods |
| 37 | + Bson searchStageFilters = Aggregates.search( |
| 38 | + SearchOperator.compound() |
| 39 | + .filter( |
| 40 | + List.of( |
| 41 | + SearchOperator.text(fieldPath("genres"), "Drama"), |
| 42 | + SearchOperator.phrase(fieldPath("cast"), "sylvester stallone"), |
| 43 | + SearchOperator.numberRange(fieldPath("year")).gtLt(1980, 1989), |
| 44 | + SearchOperator.wildcard(fieldPath("title"),"Rocky *") |
| 45 | + ))); |
| 46 | + |
| 47 | + Bson projection = Aggregates.project(Projections.fields( |
| 48 | + Projections.include("title", "year", "genres", "cast") |
| 49 | + )); |
| 50 | + |
| 51 | + List<Bson> aggregateStages = List.of(searchStageFilters,projection); |
| 52 | + |
| 53 | + Publisher<Document> publisher = movies.aggregate(aggregateStages); |
| 54 | + publisher.subscribe(new SubscriberHelpers.PrintDocumentSubscriber()); |
| 55 | + Mono.from(publisher).block(); |
| 56 | + // end atlasHelperMethods |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments