Skip to content

MongoCollection

A collection stores related documents together.

Usually, all documents in a collection have the same shape (the same fields). However, heterogeneous structure can be achieved by using:

  • Kotlin collections, like List and Set, the embed an arbitrary number of items.

  • Polymorphism, for example with sealed class, to have different fields based on a discriminator.

To avoid name collisions, collections are grouped into databases.

To obtain a collection, see MongoDatabase.collection.

Size limit

A MongoDB document cannot exceed 16 MiB.

You can measure the size of a document with opensavvy.ktmongo.bson.BsonDocument.toByteArray followed by ByteArray.size.

The maximum nesting is 100 levels. Each document or array adds a level.

Operations

The following lists the available operations using the mongosh equivalent:

External resources

Properties

context

The full BSON configuration, used by the DSL to generate queries.

factory

abstract val factory: BsonFactory

The BsonFactory used to serialize and deserialize values stored in this collection.

This property stores all serialization configurations and allows creating custom BSON objects.

For more information, see BsonFactory.

fullyQualifiedName

abstract val fullyQualifiedName: String

The concatenation of the database's name and the collection's name, separated by a dot (.).

name

abstract val name: String

THe name of this collection.

The collection name must be unique within a single database (otherwise, the two instances refer to the same data).

  • The name should begin with a letter or an underscore (_).

  • The name cannot be empty.

  • The name cannot contain the null character nor the $ character.

  • The name cannot being with system..

  • The name cannot contain .system..

  • It is recommended to avoid names longer than 171 bytes.

External resources

objectIdGenerator

The algorithm used to generate new ObjectId instances for this collection.

For more information, see ObjectIdGenerator.

You can also directly call newId on the collection itself.

propertyNameStrategy

The strategy used to convert property names to BSON document keys.

For more information, see PropertyNameStrategy.

type

@LowLevelApi
abstract val type: KType

The KType instance that corresponds to the collection's document type.

This property is used by serialization libraries to know the exact type to deserialize, especially in the presence of type parameters.

Everyday users should not need to interact with this property directly.

Functions

aggregate

Starts an aggregation pipeline on this collection.

bulkWrite

abstract suspend fun bulkWrite(
    options: BulkWriteOptions<Document>.() -> Unit = {}, 
    filter: FilterQuery<Document>.() -> Unit = {}, 
    operations: BulkWrite<Document>.() -> Unit
)

Performs multiple update operations in a single request.

count

abstract suspend fun count(): Long

Counts how many documents exist in the collection.

abstract suspend fun count(options: CountOptions<Document>.() -> Unit = {}, predicate: FilterQuery<Document>.() -> Unit): Long

Counts how many documents match predicate in the collection.

countEstimated

abstract suspend fun countEstimated(): Long

Counts all documents in the collection.

deleteMany

abstract suspend fun deleteMany(options: DeleteManyOptions<Document>.() -> Unit = {}, filter: FilterQuery<Document>.() -> Unit)

Deletes all documents that match filter.

deleteOne

abstract suspend fun deleteOne(options: DeleteOneOptions<Document>.() -> Unit = {}, filter: FilterQuery<Document>.() -> Unit)

Deletes the first document found that matches filter.

drop

abstract suspend fun drop(options: DropOptions<Document>.() -> Unit = {})

Removes an entire collection from the database.

exists

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

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

filter

abstract override fun filter(filter: FilterQuery<Document>.() -> Unit): MongoCollection<Document>

Creates a client-side view containing all the documents that match filter.

Client-side views

MongoDB has a concept of views: read-only results of aggregation pipelines useful to avoid repeating the same queries in multiple places.

This function does not create a MongoDB view. Instead, it creates a logical view, which is purely syntax sugar in the KtMongo library and doesn't exist in MongoDB itself. The database is never aware of client-side views.

Client-side views do not have the limitations of real MongoDB views: they can be mutable and support all operators.

Essentially, this method returns a MongoCollection implementation that combines the filter with every filter provided by any other operation, using a $and.

Example

Let's imagine you want to implement logical deletion of items:

class Parcel(
    val _id: ObjectId,
    val owner: ObjectId,
    val isActive: Boolean = true,
)

In that situation, you will need to remember to apply a filter in almost all methods you implement:

// Find the user's active parcels
parcels.find({ sort { descending(Parcel::_id) } }) {
    Parcel::owner eq currentUserId()
    Parcel::isActive ne false  // ⚠ Don't forget!
}

// An owner transfers all active parcels to another one
parcels.updateMany(
    filter = {
        Parcel::owner eq currentUserId()
        Parcel::isActive ne false  // ⚠ Don't forget!
    },
    update = {
        Parcel::owner set transferDestinationUserId
    }
)

To avoid worrying about specifying the same filter each time, you can use client-side logical views to factor it out into a subset collection:

val activeParcels = parcels.filter { Parcel::isActive ne false }

// Find the user's active parcels
activeParcels.find({ sort { descending(Parcel::_id) } }) {
    Parcel::owner eq currentUserId()
}

// An owner transfers all active parcels to another one
activeParcels.updateMany(
    filter = { Parcel::owner eq currentUserId() },
    update = { Parcel::owner set transferDestinationUserId }
)

This example is strictly identical to the previous one: the driver combines the client-side view's and the operation's filters.

A client-side view can be created from another one, which allows to further shorten the update:

// An owner transfers all active parcels to another one
activeParcels.filter { Parcel::owner eq currentUserId() }
    .updateMany { Parcel::owner set transferDestinationUserId }

This style, using an explicit filter function instead of using the operation's own filter, allows using Kotlin's trailing syntax. We encourage its usage, there is no performance impact.

Learn more in the KtMongo feature page.

find

abstract fun find(): MongoIterable<Document>

Finds all documents in this collection.

abstract fun find(options: FindOptions<Document>.() -> Unit = {}, filter: FilterQuery<Document>.() -> Unit): MongoIterable<Document>

Finds all documents in this collection that satisfy filter.

findOne

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

Finds a document in this collection that satisfies filter.

findOneAndUpdate

abstract suspend 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.

insertMany

abstract suspend fun insertMany(documents: Iterable<Document>, options: InsertManyOptions<Document>.() -> Unit = {})

Inserts multiple documents in a single operation.

open suspend fun insertMany(vararg documents: Document, options: InsertManyOptions<Document>.() -> Unit = {})

Inserts multiple documents in a single operation.

insertOne

abstract suspend fun insertOne(document: Document, options: InsertOneOptions<Document>.() -> Unit = {})

Inserts a document.

newId

open override fun newId(): ObjectId

replaceOne

abstract suspend fun replaceOne(
    options: ReplaceOptions<Document>.() -> Unit = {}, 
    filter: FilterQuery<Document>.() -> Unit = {}, 
    document: Document
)

Replaces a document that matches filter by document.

repsertOne

abstract suspend fun repsertOne(
    options: ReplaceOptions<Document>.() -> Unit = {}, 
    filter: FilterQuery<Document>.() -> Unit = {}, 
    document: Document
)

Replaces a document that matches filter by document.

updateMany

@IgnorableReturnValue
abstract suspend 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.

updateManyWithPipeline

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

updateOne

@IgnorableReturnValue
abstract suspend 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.

updateOneWithPipeline

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

upsertOne

@IgnorableReturnValue
abstract suspend 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.

upsertOneWithPipeline

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