|
| 1 | +import com.mongodb.client.model.Aggregates.limit |
| 2 | +import com.mongodb.client.model.Aggregates.project |
| 3 | +import com.mongodb.client.model.Filters.eq |
| 4 | +import com.mongodb.client.model.Projections.* |
| 5 | +import com.mongodb.kotlin.client.coroutine.MongoClient |
| 6 | +import kotlinx.coroutines.runBlocking |
| 7 | +import org.bson.Document |
| 8 | + |
| 9 | +fun main() { |
| 10 | + val uri = "<connection string>" |
| 11 | + val mongoClient = MongoClient.create(uri) |
| 12 | + |
| 13 | + val database = mongoClient.getDatabase("local_school_district") |
| 14 | + val collection = database.getCollection<Document>("schools") |
| 15 | + |
| 16 | + runBlocking { |
| 17 | + val agg = Document("index", "compound-query-custom-score-tutorial") |
| 18 | + .append( |
| 19 | + "must", listOf( |
| 20 | + Document( |
| 21 | + "text", |
| 22 | + Document("path", "genres") |
| 23 | + .append("query", "comedy") |
| 24 | + .append( |
| 25 | + "score", |
| 26 | + Document( |
| 27 | + "boost", |
| 28 | + Document("value", 9) |
| 29 | + ) |
| 30 | + ) |
| 31 | + ), |
| 32 | + Document( |
| 33 | + "text", |
| 34 | + Document("path", "title") |
| 35 | + .append("query", "snow") |
| 36 | + .append( |
| 37 | + "score", |
| 38 | + Document( |
| 39 | + "boost", |
| 40 | + Document("value", 5) |
| 41 | + ) |
| 42 | + ) |
| 43 | + ) |
| 44 | + ) |
| 45 | + ) |
| 46 | + .append( |
| 47 | + "should", listOf( |
| 48 | + Document( |
| 49 | + "range", |
| 50 | + Document("path", "year") |
| 51 | + .append("gte", 2013) |
| 52 | + .append("lte", 2015) |
| 53 | + .append( |
| 54 | + "score", |
| 55 | + Document( |
| 56 | + "boost", |
| 57 | + Document("value", 3) |
| 58 | + ) |
| 59 | + ) |
| 60 | + ) |
| 61 | + ) |
| 62 | + ) |
| 63 | + |
| 64 | + val resultsFlow = collection.aggregate<Document>( |
| 65 | + listOf( |
| 66 | + eq("\$search", eq("compound", agg)), |
| 67 | + limit(10), |
| 68 | + project(fields( |
| 69 | + excludeId(), |
| 70 | + include("title", "year","genres"), |
| 71 | + computed("score", Document("\$meta", "searchScore")) |
| 72 | + )) |
| 73 | + ) |
| 74 | + ) |
| 75 | + resultsFlow.collect { println(it) } |
| 76 | + } |
| 77 | + mongoClient.close() |
| 78 | +} |
| 79 | + |
0 commit comments