Skip to content

JvmMongoCollection

Implementation of MongoCollection based on MongoDB's MongoCollection.

To access the inner iterable, see asKotlinClient.

To convert an existing MongoDB iterable into an instance of this class, see asKtMongo.

Properties

context

@LowLevelApi



open override val context: JvmBsonContext

Functions

aggregate

Start an aggregation pipeline.

Example
class User(
    val name: String,
    val age: Int,
)

users.aggregate()
    .match { User::age gt 18 }
    .toList()
External resources

asKotlinClient

@LowLevelApi



fun asKotlinClient(): MongoCollection<Document>

bulkWrite

open override fun bulkWrite(
    options: BulkWriteOptions<Document>.() -> Unit, 
    filter: FilterQuery<Document>.() -> Unit, 
    operations: BulkWrite<Document>.() -> Unit
)

Performs multiple update operations in a single request.

Example
class User(
    val name: String,
    val age: Int,
)

collection.bulkWrite {
    upsertOne(
        filter = {
            User::name eq "Patrick"
        },
        update = {
            User::age set 15
        }
    )

    updateMany {
        User::age inc 1
    }
}

To see which operations are available and their respective syntax, see BulkWrite.

Using filtered writes

We can group operations by the filter they apply on:

collection.bulkWrite {
    filtered(filter = { User::isAlive eq true }) {
        updateOne()
        updateOne()
        updateMany()
    }

    updateOne()
}

To learn more, see filtered.

Using filtered collections

If we want all operations to use the same filter, we can declare it before calling the operation:

collection.filter {
    User::isAlive eq true
}.bulkWrite {
    updateOne()
    updateOne()
    updateMany()
}
External resources

count

open override fun count(): Long

Counts how many documents exist in the collection.

External resources

See also

open override fun count(options: CountOptions<Document>.() -> Unit, predicate: FilterQuery<Document>.() -> Unit): Long

Counts how many documents match predicate in the collection.

Example
class User(
    val name: String,
    val age: Int,
)

collection.count {
    User::name eq "foo"
    User::age eq 10
}
External resources

countEstimated

open override fun countEstimated(): Long

Counts all documents in the collection.

This function reads collection metadata instead of actually counting through all documents. This makes it much more performant (almost no CPU nor RAM usage), but the count may be slightly out of date.

In particular, it may become inaccurate when:

  • there are orphaned documents in a shared cluster,

  • an unclean shutdown happened.

Views do not possess the required metadata. When this function is called on a view (either a MongoDB view or a filter logical view), a regular count is executed instead.

External resources

See also

deleteMany

open override fun deleteMany(options: DeleteManyOptions<Document>.() -> Unit, filter: FilterQuery<Document>.() -> Unit)

Deletes all documents that match filter.

Example
class User(
    val name: String,
    val age: Int
)

collection.deleteMany {
    User::age lt 18
}
External resources

deleteOne

open override fun deleteOne(options: DeleteOneOptions<Document>.() -> Unit, filter: FilterQuery<Document>.() -> Unit)

Deletes the first document found that matches filter.

Example
class User(
    val name: String,
    val age: Int
)

collection.deleteOne {
    User::name eq "Bob"
}
External resources

drop

open override fun drop(options: DropOptions<Document>.() -> Unit)

Removes an entire collection from the database.

Example
collection.drop()
Using with filtered collections

When using filtered collections, all elements matching the filter are removed. Other documents are not impacted, and the collection is not deleted.

External resources

exists

open fun exists(options: CountOptions<Document>.() -> Unit, predicate: FilterQuery<Document>.() -> Unit): Boolean

Tests if there exists a document that matches predicate in the collection.

filter

Returns a filtered collection that only contains the elements that match filter.

This function creates a logical view of the collection: by itself, this function does nothing, and MongoDB is never aware of the existence of this logical view. However, operations invoked on the returned collection will only affect elements from the original that match the filter.

Unlike actual MongoDB views, which are read-only, collections returned by this function can also be used for write operations.

Example

A typical usage of this function is to reuse filters for multiple operations. For example, if you have a concept of logical deletion, this function can be used to hide deleted values.

class Order(
    val id: String,
    val date: Instant,
    val deleted: Boolean,
)

val allOrders = database.getCollection<Order>("orders").asKtMongo()
val activeOrders = allOrders.filter { Order::deleted ne true }

allOrders.find()    // Returns all orders, deleted or not
activeOrders.find() // Only returns orders that are not logically deleted

find

open override fun find(): JvmMongoIterable<Document>

Finds all documents in this collection.

External resources
open override fun find(options: FindOptions<Document>.() -> Unit, filter: FilterQuery<Document>.() -> Unit): JvmMongoIterable<Document>

Finds all documents in this collection that satisfy filter.

If multiple predicates are specified, an and operator is implied.

Example
class User(
    val name: String,
    val age: Int,
)

collection.find {
    User::name eq "foo"
    User::age eq 10
}
External resources

See also

findOne

open fun findOne(options: FindOptions<Document>.() -> Unit, filter: FilterQuery<Document>.() -> Unit): Document?

Finds a document in this collection that satisfies filter.

findOneAndUpdate

open override fun findOneAndUpdate(
    options: UpdateOptions<Document>.() -> Unit, 
    filter: FilterQuery<Document>.() -> Unit, 
    update: UpdateQuery<Document>.() -> Unit
): Document?

Updates one element that matches filter according to update and returns it, atomically.

Example
class User(
    val name: String,
    val age: Int,
)

collection.findOneAndUpdate(
    filter = {
        User::name eq "Patrick"
    },
    update = {
        User::age set 15
    },
)
Using filtered collections

The following code is equivalent:

collection.filter {
    User::name eq "Patrick"
}.findOneAndUpdate {
    User::age set 15
}

To learn more, see filter.

External resources

Parameters

  • filter: Optional filter to select which document is updated. If no filter is specified, the first document found is updated.

See also

insertMany

open override fun insertMany(documents: Iterable<Document>, options: InsertManyOptions<Document>.() -> Unit)

Inserts multiple documents in a single operation.

Example
class User(
    val name: String,
    val age: Int,
)

collection.insertMany(users)

Note that insertOne ignores filtered collection. That is, insertOne on a filtered collection behaves exactly the same as the same insertOne on the underlying real collection.

External resources

See also

insertOne

open override fun insertOne(document: Document, options: InsertOneOptions<Document>.() -> Unit)

Inserts a document.

Example
class User(
    val name: String,
    val age: Int,
)

collection.insertOne(User(name = "Bob", age = 18))

Note that insertOne ignores filtered collection. That is, insertOne on a filtered collection behaves exactly the same as the same insertOne on the underlying real collection.

External resources

See also

newId

open override fun newId(): ObjectId

replaceOne

open override fun replaceOne(
    options: ReplaceOptions<Document>.() -> Unit, 
    filter: FilterQuery<Document>.() -> Unit, 
    document: Document
)

Replaces a document that matches filter by document.

If multiple documents match filter, only the first one found is updated.

Data races

This operator is often used by first reading a document, processing it, and replacing it. This can be dangerous in distributed systems because another replica of the server could have updated the document between the read and the write.

If this is a concern, it is recommended to use updateOne with explicit operators on the data that has changed, allowing to do the modification in a single operation. Doing the update that way, MongoDB is responsible for ensuring the read and the write are atomic.

Example
class User(
    val name: String,
    val age: Int,
)

collection.replaceOne(
    filter = {
        User::name eq "Patrick"
    },
    document = User("Bob", 15)
)
Using filtered collections

The following code is equivalent:

collection.filter {
    User::name eq "Patrick"
}.replaceOne(User("Patrick", 15))

To learn more, see filter.

External resources

Parameters

  • filter: Optional filter to select which document is updated. If no filter is specified, the first document found is updated.

See also

repsertOne

open override fun repsertOne(
    options: ReplaceOptions<Document>.() -> Unit, 
    filter: FilterQuery<Document>.() -> Unit, 
    document: Document
)

Replaces a document that matches filter by document.

If multiple documents match filter, only the first one found is updated.

If no documents match filter, document is inserted.

Data races

This operator is often used by first reading a document, processing it, and replacing it. This can be dangerous in distributed systems because another replica of the server could have updated the document between the read and the write.

If this is a concern, it is recommended to use updateOne with explicit operators on the data that has changed, allowing to do the modification in a single operation. Doing the update that way, MongoDB is responsible for ensuring the read and the write are atomic.

Example
class User(
    val name: String,
    val age: Int,
)

collection.repsertOne(
    filter = {
        User::name eq "Patrick"
    },
    document = User("Bob", 15)
)
Using filtered collections

The following code is equivalent:

collection.filter {
    User::name eq "Patrick"
}.repsertOne(User("Patrick", 15))

To learn more, see filter.

External resources

Parameters

  • filter: Optional filter to select which document is updated. If no filter is specified, the first document found is updated.

See also

toString

open override fun toString(): String

updateMany

open override fun updateMany(
    options: UpdateOptions<Document>.() -> Unit, 
    filter: FilterQuery<Document>.() -> Unit, 
    update: UpdateQuery<Document>.() -> Unit
): UpdateOperations.UpdateResult

Updates all documents that match filter according to update.

Example
class User(
    val name: String,
    val age: Int,
)

collection.updateMany(
    filter = {
        User::name eq "Patrick"
    },
    update = {
        User::age set 15
    },
)
Using filtered collections

The following code is equivalent:

collection.filter {
    User::name eq "Patrick"
}.updateMany {
    User::age set 15
}

To learn more, see filter.

External resources

Parameters

  • filter: Optional filter to select which documents are updated. If no filter is specified, all documents are updated.

See also

updateManyWithPipeline

Updates all documents that match filter according to the update pipeline.

Example
class User(
    val name: String,
    val age: Int,
)

collection.updateManyWithPipeline(
    filter = {
        User::name eq "Patrick"
    }
) {
    set {
        User::age set 15
    }
}
External resources

Parameters

  • filter: Optional filter to select which documents are updated. If no filter is specified, all documents are updated.

See also

updateOne

open override fun updateOne(
    options: UpdateOptions<Document>.() -> Unit, 
    filter: FilterQuery<Document>.() -> Unit, 
    update: UpdateQuery<Document>.() -> Unit
): UpdateOperations.UpdateResult

Updates a single document that matches filter according to update.

If multiple documents match filter, only the first one found is updated.

Example
class User(
    val name: String,
    val age: Int,
)

collection.updateOne(
    filter = {
        User::name eq "Patrick"
    },
    update = {
        User::age set 15
    },
)
Using filtered collections

The following code is equivalent:

collection.filter {
    User::name eq "Patrick"
}.updateOne {
    User::age set 15
}

To learn more, see filter.

External resources

Parameters

  • filter: Optional filter to select which document is updated. If no filter is specified, the first document found is updated.

See also

updateOneWithPipeline

Updates a single document that matches filter according to the update pipeline.

If multiple documents match filter, only the first one found is updated.

Example
class User(
    val name: String,
    val age: Int,
)

collection.updateOneWithPipeline(
    filter = {
        User::name eq "Patrick"
    }
) {
    set {
        User::age set 15
    }
}
External resources

Parameters

  • filter: Optional filter to select which document is updated. If no filter is specified, the first document found is updated.

See also

upsertOne

open override fun upsertOne(
    options: UpdateOptions<Document>.() -> Unit, 
    filter: FilterQuery<Document>.() -> Unit, 
    update: UpsertQuery<Document>.() -> Unit
): UpdateOperations.UpsertResult

Updates a single document that matches filter according to update.

If multiple documents match filter, only the first one is updated.

If no documents match filter, a new one is created.

Example
class User(
    val name: String,
    val age: Int,
)

collection.upsertOne(
    filter = {
        User::name eq "Patrick"
    },
    update = {
        User::age set 15
    },
)

If a document exists that has the name of "Patrick", its age is set to 15. If none exists, a document with name "Patrick" and age 15 is created.

Using filtered collections

The following code is equivalent:

collection.filter {
    User::name eq "Patrick"
}.upsertOne {
    User::age set 15
}

To learn more, see filter.

External resources

See also

upsertOneWithPipeline

Updates a single document that matches filter according to the update pipeline.

If multiple documents match filter, only the first one is updated.

If no documents match filter, a new one is created.

Example
class User(
    val name: String,
    val age: Int,
)

collection.upsertOneWithPipeline(
    filter = {
         User::name eq "Patrick"
    }
) {
    set {
        User::age set 15
    }
}
External resources

See also