filter

fun <Document : Any> MongoCollection<Document>.filter(filter: <Error class: unknown class><Document>.() -> Unit): MongoCollection<Document>(source)

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