| collection.find( | Filters.eq(Movie::title.name, "Shrek") | ).firstOrNull() |
|
| collection.find( | Filters.eq(Movie::year.name, 2004) | ) |
|
| collection.insertOne(Movie("Shrek", 2001)) |
|
Insert Multiple Documents
| collection.insertMany( | listOf( | Movie("Shrek", 2001), | Movie("Shrek 2", 2004), | Movie("Shrek the Third", 2007), | Movie("Shrek Forever After", 2010), | ) | ) |
|
| collection.updateOne( | Filters.eq(Movie::title.name, "Shrek"), | Updates.set(Movie::rated.name, "PG") | ) |
|
Update Multiple Documents
| collection.updateMany( | Filters.regex(Movie::title.name, "Shrek"), | Updates.set(Movie::rated.name, "PG") | ) |
|
Update an Array in a Document
| collection.updateOne( | Filters.eq(Movie::title.name, "Shrek"), | Updates.addEachToSet(Movie::genres.name, listOf("Family", "Fantasy")) | ) |
|
| collection.replaceOne( | Filters.eq(Movie::title.name, "Shrek"), | Movie("Kersh", 1002, "GP") | ) |
|
| collection.deleteOne( | Filters.eq(Movie::title.name, "Shrek") | ) |
|
Delete Multiple Documents
| collection.deleteMany( | Filters.regex(Movie::title.name, "Shrek") | ) |
|
| collection.bulkWrite( | listOf( | InsertOneModel(Movie("Shrek", 2001)), | DeleteManyModel(Filters.lt(Movie::year.name, 2004)), | ) | ) |
|
| val changeStream = collection.watch() | changeStream.collect { | println("Change to ${it.fullDocument?.title}") | } |
|
Access Results from a Query as a List | collection.find().toList() |
|
| collection.countDocuments(Filters.eq("year", 2001)) |
|
List the Distinct Documents or Field Values | collection.distinct<String>(Movie::rated.name) |
|
Limit the Number of Documents Retrieved
| collection.find() | .limit(2) |
|
| collection.find() | .skip(2) |
|
Sort the Documents When Retrieving Them
| collection.find().sort(Sorts.descending(Movie::year.name)) |
|
Project Document Fields When Retrieving Them
| data class Result(val title: String) | collection.find<Result>() | .projection(Projections.include(Movie::title.name)) |
|
| collection.createIndex(Indexes.ascending(Movie::title.name)) |
|
| collection.find(Filters.text("Forever")); |
|
Install the Driver Dependency with Maven | <dependencies> | <dependency> | <groupId>org.mongodb</groupId> | <artifactId>mongodb-driver-kotlin-coroutine</artifactId> | <version>5.2.0</version> | </dependency> | </dependencies> |
|
Install the Driver Dependency with Gradle | dependencies { | implementation("org.mongodb:mongodb-driver-kotlin-coroutine:5.2.0") | } |
|
Access Data from a Flow Iteratively
| val flow = collection.find( | Filters.eq(Movie::year.name, 2004) | ) | flow.collect { println(it) } |
|