Skip to content

CountOperations

The different MongoDB operations related to counting documents.

Inheritors

Properties

context

abstract val context: BsonContext

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

For more information, see BsonContext.

factory

abstract val factory: BsonFactory

The BsonFactory used to serialize and deserialize values.

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

For more information, see BsonFactory.

objectIdGenerator

The algorithm used to generate new ObjectId instances.

For more information, see ObjectIdGenerator.

propertyNameStrategy

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

For more information, see PropertyNameStrategy.

Functions

count

abstract fun count(): Long

Counts how many documents exist in the collection.

Implementation

This method, just like in mongosh, in syntax sugar for an aggregation pipeline using the countTo stage.

External resources

See also

  • countEstimated: Faster alternative when the result doesn't need to be exact.
abstract 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
}

Implementation

This method, just like in mongosh, in syntax sugar for an aggregation pipeline using the match and the countTo stages.

External resources

countEstimated

abstract fun countEstimated(): Long

Counts all documents in the collection.

Implementation

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.

Example

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

collection.countEstimated()

External resources

See also

  • count: Perform the count for real.

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.

This method is a convenience function for calling count with a limit of 1.

Example

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

collection.exists {
    User::name eq "foo"
    User::age eq 10
}