Skip to content

Commit 8c99f99

Browse files
committed
add query examples
1 parent 11bd648 commit 8c99f99

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
val database = mongoClient.getDatabase("sample_mflix")
13+
val collection = database.getCollection<Document>("movies")
14+
15+
runBlocking {
16+
val agg = Document(
17+
"must", listOf(
18+
Document("text", Document("query", listOf("Hawaii", "Alaska"))
19+
.append("path", "plot")),
20+
Document(
21+
"regex",
22+
Document("query", "([0-9]{4})")
23+
.append("path", "plot")
24+
.append("allowAnalyzedField", true)
25+
)
26+
)
27+
)
28+
.append(
29+
"mustNot", listOf(
30+
Document("text", Document("query", listOf("Comedy", "Romance"))
31+
.append("path", "genres")),
32+
Document("text", Document("query", listOf("Beach", "Snow"))
33+
.append("path", "title"))
34+
)
35+
)
36+
37+
val resultsFlow = collection.aggregate<Document>(
38+
listOf(
39+
eq("\$search", eq("compound", agg)),
40+
project(fields(
41+
excludeId(),
42+
include("title", "plot", "genres")
43+
))
44+
)
45+
)
46+
47+
resultsFlow.collect { println(it) }
48+
}
49+
50+
mongoClient.close()
51+
}
52+
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
val database = mongoClient.getDatabase("sample_mflix")
13+
val collection = database.getCollection<Document>("movies")
14+
15+
runBlocking {
16+
val agg = Document("query", "baseball").append("path","plot")
17+
18+
val resultsFlow = collection.aggregate<Document>(
19+
listOf(
20+
eq("\$search", eq("text", agg)),
21+
limit(5),
22+
project(fields(excludeId(), include("title", "plot")))
23+
)
24+
)
25+
26+
resultsFlow.collect { println(it) }
27+
}
28+
29+
mongoClient.close()
30+
}
31+

0 commit comments

Comments
 (0)