|
| 1 | +import com.mongodb.client.model.Aggregates |
| 2 | +import com.mongodb.client.model.Projections |
| 3 | +import com.mongodb.client.model.search.SearchOperator |
| 4 | +import com.mongodb.client.model.search.SearchPath.fieldPath |
| 5 | +import com.mongodb.kotlin.client.coroutine.MongoClient |
| 6 | +import kotlinx.coroutines.runBlocking |
| 7 | +import org.bson.Document |
| 8 | +import org.bson.conversions.Bson |
| 9 | +import java.io.IO.println |
| 10 | +import kotlin.collections.List |
| 11 | + |
| 12 | +const val URI = "<connection-string>" |
| 13 | + |
| 14 | +// Create data class to represent a MongoDB document |
| 15 | +data class Movie(val title: String, val year: Int, val cast: List<String>) |
| 16 | + |
| 17 | +fun main() { |
| 18 | + |
| 19 | + // Replace the placeholder with your MongoDB deployment's connection string |
| 20 | + val uri = URI |
| 21 | + |
| 22 | + val mongoClient = MongoClient.create(uri) |
| 23 | + val database = mongoClient.getDatabase("sample_mflix") |
| 24 | + // Get a collection of documents of type Movie |
| 25 | + val collection = database.getCollection<Movie>("movies") |
| 26 | + |
| 27 | + // start atlasHelperMethods |
| 28 | + runBlocking { |
| 29 | + val searchStage: Bson = Aggregates.search( |
| 30 | + SearchOperator.compound() |
| 31 | + .filter( |
| 32 | + listOf( |
| 33 | + SearchOperator.text(fieldPath("genres"), "Drama"), |
| 34 | + SearchOperator.phrase(fieldPath("cast"), "sylvester stallone"), |
| 35 | + SearchOperator.numberRange(fieldPath("year")).gtLt(1980, 1989), |
| 36 | + SearchOperator.wildcard(fieldPath("title"), "Rocky *") |
| 37 | + ) |
| 38 | + ) |
| 39 | + ) |
| 40 | + |
| 41 | + val projection = Projections.fields( |
| 42 | + Projections.include("title", "year", "genres", "cast") |
| 43 | + ) |
| 44 | + |
| 45 | + val aggregatePipelineStages: List<Bson> = listOf(searchStage, Aggregates.project(projection)) |
| 46 | + val results = collection.aggregate<Document>(aggregatePipelineStages) |
| 47 | + |
| 48 | + results.collect { println(it) } |
| 49 | + } |
| 50 | + // end atlasHelperMethods |
| 51 | + |
| 52 | + mongoClient.close() |
| 53 | +} |
| 54 | + |
0 commit comments