Skip to content

FilterQuery

DSL for MongoDB operators that are used as predicates in conditions.

Example

This expression type is available in multiple operators, most commonly find:

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

collection.find {
    User::age gte 18
}

Beware of arrays!

MongoDB operators do not discriminate between scalars and arrays. When an array is encountered, all operators attempt to match on the array itself. If the match fails, the operators attempt to match array elements.

It is not possible to mimic this behavior in KtMongo while still keeping type-safety, so operators may behave strangely when arrays are encountered.

Note that if the collection corresponds to the declared Kotlin type, these situations can never happen, as the Kotlin type system doesn't allow them to.

When developers attempt to perform an operator on the entire array, they should use operators as normal:

class User(
    val name: String,
    val favoriteNumbers: List<Int>
)

collection.find {
    User::favoriteNumbers eq listOf(1, 2)
}

Developers should use the request above when they want to match a document similar to:

{
    favoriteNumbers: [1, 2]
}

The following document will NOT match:

{
    favoriteNumbers: [3]
}

However, due to MongoDB's behavior when encountering arrays, it should be noted that the following document WILL match:

{
    favoriteNumbers: [
        [3],
        [1, 2],
        [7, 2]
    ]
}

To execute an operator on one of the elements of an array, see anyValue.

Operators

Comparison query:

Logical query:

Element query:

Array query:

Bitwise query:

Text query:

If you can't find an operator you're searching for, visit the tracking issue.

Constructors

FilterQuery

@LowLevelApi



fun <T> FilterQuery(context: BsonContext): FilterQuery<T>

Creates an empty FilterQuery.

Properties

any

abstract fun <V> Field<T, Collection<V>>.any(block: FilterQuery<V>.() -> Unit)

Specify multiple operators on fields of a single array element.

Example

Find customers who have a pet that is born this month, as they may be eligible for a discount.

class Customer(
    val name: String,
    val pets: List<Pet>,
)

class Pet(
    val name: String,
    val birthMonth: Int
)

val currentMonth = 3

collection.find {
    Customer::pets.any {
        Pet::birthMonth gte currentMonth
        Pet::birthMonth lte (currentMonth + 1)
    }
}

The following document will match:

{
    "name": "Fred",
    "pets": [
        {
            "name": "Arthur",
            "birthMonth": 5
        },
        {
            "name": "Gwen",
            "birthMonth": 3
        }
    ]
}

because the pet "Gwen" has a matching birth month.

If you want to perform operators on the elements directly (not on their fields), use anyValue instead.

External resources
open fun <V> KProperty1<T, Collection<V>>.any(block: FilterQuery<V>.() -> Unit)

Specify multiple operators on fields of a single array element.

Example

Find customers who have a pet that is born this month, as they may be eligible for a discount.

class Customer(
    val name: String,
    val pets: List<Pet>,
)

class Pet(
    val name: String,
    val birthMonth: Int
)

val currentMonth = 3

collection.find {
    Customer::pets.any {
        Pet::birthMonth gte currentMonth
        Pet::birthMonth lte (currentMonth + 1)
    }
}

The following document will match:

{
    "name": "Fred",
    "pets": [
        {
            "name": "Arthur",
            "birthMonth": 5
        },
        {
            "name": "Gwen",
            "birthMonth": 3
        }
    ]
}

because the pet "Gwen" has a matching birth month.

If you want to perform operators on the elements directly (not on their fields), use anyValue instead.

External resources
open val <V> Field<T, Collection<V>>.any: Field<T, V>

Specify operators on array elements.

Example

Find any user who has 12 as one of their favorite numbers.

class User(
    val name: String,
    val favoriteNumbers: List<Int>
)

collection.find {
    User::favoriteNumbers.any eq 12
}
Repeated usages will match different items

Note that if any is used multiple times, it may test different items. For example, the following request will match the following document:

collection.find {
    User::favoriteNumbers.any gt 2
    User::favoriteNumbers.any lte 7
}
{
    "name": "Nicolas",
    "favoriteNumbers": [ 1, 9 ]
}

Because 1 is less than 7, and 9 is greater than 2, the document is returned.

If you want to apply multiple filters to the same item, use the any function.

Arrays don't exist in finds!

MongoDB operators do not discriminate between scalars and arrays. When an array is encountered, all operators attempt to match on the array itself. If the match fails, the operators attempt to match array elements.

It is not possible to mimic this behavior in KtMongo while still keeping type-safety, so KtMongo has different operators to filter a collection itself or its elements.

As a consequence, the request:

collection.find {
    User::favoriteNumbers.any eq 5
}

will, as expected, match the following document:

{
    favoriteNumbers: [1, 4, 5, 10]
}

It is important to note that it WILL also match this document:

{
    favoriteNumbers: 5
}

Since this document doesn't conform to the Kotlin declared type List<Int>, it is unlikely that such an element exists, but developers should keep it in mind.

External resources
open val <V> KProperty1<T, Collection<V>>.any: Field<T, V>

Specify operators on array elements.

Example

Find any user who has 12 as one of their favorite numbers.

class User(
    val name: String,
    val favoriteNumbers: List<Int>
)

collection.find {
    User::favoriteNumbers.any eq 12
}
Repeated usages will match different items

Note that if any is used multiple times, it may test different items. For example, the following request will match the following document:

collection.find {
    User::favoriteNumbers.any gt 2
    User::favoriteNumbers.any lte 7
}
{
    "name": "Nicolas",
    "favoriteNumbers": [ 1, 9 ]
}

Because 1 is less than 7, and 9 is greater than 2, the document is returned.

If you want to apply multiple filters to the same item, use the any function.

Arrays don't exist in finds!

MongoDB operators do not discriminate between scalars and arrays. When an array is encountered, all operators attempt to match on the array itself. If the match fails, the operators attempt to match array elements.

It is not possible to mimic this behavior in KtMongo while still keeping type-safety, so KtMongo has different operators to filter a collection itself or its elements.

As a consequence, the request:

collection.find {
    User::favoriteNumbers.any eq 5
}

will, as expected, match the following document:

{
    favoriteNumbers: [1, 4, 5, 10]
}

It is important to note that it WILL also match this document:

{
    favoriteNumbers: 5
}

Since this document doesn't conform to the Kotlin declared type List<Int>, it is unlikely that such an element exists, but developers should keep it in mind.

External resources

context

@LowLevelApi



abstract val context: BsonContext

The context used to generate this expression.

field

Converts a Kotlin property into a Field.

Functions

accept

@LowLevelApi



@DangerousMongoApi



abstract override fun accept(node: BsonNode)

Adds a new node as a child of this one.

acceptAll

@LowLevelApi



@DangerousMongoApi



fun <N : Node> CompoundNode<N>.acceptAll(nodes: Iterable<N>)

Adds any number of nodes into this one.

and

abstract fun and(block: FilterQuery<T>.() -> Unit)

Performs a logical AND operation on one or more expressions, and selects the documents that satisfy all the expressions.

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

collection.findOne {
    and {
        User::name eq "foo"
        User::age eq 18
    }
}
External resources

See also

anyValue

abstract fun <V> Field<T, Collection<V>>.anyValue(block: FilterQueryPredicate<V>.() -> Unit)

Specify multiple operators on a single array element.

Example

Find students with a grade between 8 and 10, that may be eligible to perform an exam a second time.

class Student(
    val name: String,
    val grades: List<Int>
)

collection.find {
    Student::grades.anyValue {
        gte(8)
        lte(10)
    }
}

The following document will match because the grade 9 is in the interval.

{
    "name": "John",
    "grades": [9, 3]
}

The following document will NOT match, because none of the grades are in the interval.

{
    "name": "Lea",
    "grades": [18, 19]
}

If you want to perform multiple checks on different elements of an array, see the any property.

This function only allows specifying operators on array elements directly. To specify operators on sub-fields of array elements, see any.

External resources
open fun <V> KProperty1<T, Collection<V>>.anyValue(block: FilterQueryPredicate<V>.() -> Unit)

Specify multiple operators on a single array element.

Example

Find students with a grade between 8 and 10, that may be eligible to perform an exam a second time.

class Student(
    val name: String,
    val grades: List<Int>
)

collection.find {
    Student::grades.anyValue {
        gte(8)
        lte(10)
    }
}

The following document will match because the grade 9 is in the interval.

{
    "name": "John",
    "grades": [9, 3]
}

The following document will NOT match, because none of the grades are in the interval.

{
    "name": "Lea",
    "grades": [18, 19]
}

If you want to perform multiple checks on different elements of an array, see the any property.

This function only allows specifying operators on array elements directly. To specify operators on sub-fields of array elements, see any.

External resources

bitsAllClear

open infix fun Field<T, *>.bitsAllClear(mask: UInt)

Matches documents where all bit positions present in mask are clear (i.e., 0) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

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

collection.find {
    User::age bitsAllClear UInt.MAX_VALUE
}
Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun KProperty1<T, *>.bitsAllClear(mask: UInt)

Matches documents where all bit positions present in mask are clear (i.e., 0) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

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

collection.find {
    User::age bitsAllClear UInt.MAX_VALUE
}
Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun Field<T, *>.bitsAllClear(mask: ByteArray)

Matches documents where all bit positions present in mask are clear (i.e., 0) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun KProperty1<T, *>.bitsAllClear(mask: ByteArray)

Matches documents where all bit positions present in mask are clear (i.e., 0) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources

bitsAllSet

open infix fun Field<T, *>.bitsAllSet(mask: UInt)

Matches documents where all bit positions present in mask are set (i.e., 1) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

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

collection.find {
    User::age bitsAllSet UInt.MAX_VALUE
}
Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun KProperty1<T, *>.bitsAllSet(mask: UInt)

Matches documents where all bit positions present in mask are set (i.e., 1) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

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

collection.find {
    User::age bitsAllSet UInt.MAX_VALUE
}
Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun Field<T, *>.bitsAllSet(mask: ByteArray)

Matches documents where all bit positions present in mask are set (i.e., 1) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun KProperty1<T, *>.bitsAllSet(mask: ByteArray)

Matches documents where all bit positions present in mask are set (i.e., 1) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources

bitsAnyClear

open infix fun Field<T, *>.bitsAnyClear(mask: UInt)

Matches documents where any bit position present in mask is clear (i.e., 0) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

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

collection.find {
    User::age bitsAnyClear UInt.MAX_VALUE
}
Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun KProperty1<T, *>.bitsAnyClear(mask: UInt)

Matches documents where any bit position present in mask is clear (i.e., 0) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

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

collection.find {
    User::age bitsAnyClear UInt.MAX_VALUE
}
Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun Field<T, *>.bitsAnyClear(mask: ByteArray)

Matches documents where any bit position present in mask is clear (i.e., 0) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun KProperty1<T, *>.bitsAnyClear(mask: ByteArray)

Matches documents where any bit position present in mask is clear (i.e., 0) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources

bitsAnySet

open infix fun Field<T, *>.bitsAnySet(mask: UInt)

Matches documents where any bit position present in mask is set (i.e., 1) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

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

collection.find {
    User::age bitsAnySet UInt.MAX_VALUE
}
Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun KProperty1<T, *>.bitsAnySet(mask: UInt)

Matches documents where any bit position present in mask is set (i.e., 1) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

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

collection.find {
    User::age bitsAnySet UInt.MAX_VALUE
}
Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun Field<T, *>.bitsAnySet(mask: ByteArray)

Matches documents where any bit position present in mask is set (i.e., 1) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources
open infix fun KProperty1<T, *>.bitsAnySet(mask: ByteArray)

Matches documents where any bit position present in mask is set (i.e., 1) in the current field.

This operator will not match numerical values that cannot be represented as a signed 64-bit integer (e.g. Decimal128) nor ones that have a fractional component.

Performance

Queries cannot use indexes for this operator, but they can use indexes for other operators.

External resources

containsAll

abstract infix fun <V> Field<T, Collection<V>>.containsAll(values: Collection<V>)

Selects documents where the value of a field is an array that contains all the specified values.

Example
class User(
    val grades: List<Int>
)

collection.find {
    User::grades containsAll listOf(2, 3, 7)
}
External resources
open infix fun <V> KProperty1<T, Collection<V>>.containsAll(values: Collection<V>)

Selects documents where the value of a field is an array that contains all the specified values.

Example
class User(
    val grades: List<Int>
)

collection.find {
    User::grades containsAll listOf(2, 3, 7)
}
External resources

div

open operator fun <Root, Parent, Child> KProperty1<Root, Parent>.div(child: KProperty1<Parent & Any, Child>): Field<Root, Child>

Refers to child as a nested field of the current field.

open operator fun <Root, Type, Child> Field<Root, Type>.div(child: KProperty1<in Type & Any, Child>): Field<Root, Child>

Refers to child as a nested field of the current field.

open operator fun <Root, Type, Child> Field<Root, Type>.div(child: Field<Type, Child>): Field<Root, Child>

Refers to child as a nested field of the current field.

@JvmName
(name = "divAny")open operator fun <V, V2> KProperty1<T, Collection<V>>.div(other: KProperty1<V, V2>): Field<T, V2>

Combines Kotlin properties into a path usable to point to any item in an array.

@JvmName
(name = "divAny")open operator fun <V, V2> KProperty1<T, Collection<V>>.div(other: Field<V, V2>): Field<T, V2>

Combines Kotlin properties into a path usable to point to any item in an array.

@JvmName
(name = "divAny")open operator fun <V, V2> Field<T, Collection<V>>.div(other: KProperty1<V, V2>): Field<T, V2>

Combines Kotlin properties into a path usable to point to any item in an array.

@JvmName
(name = "divAny")open operator fun <V, V2> Field<T, Collection<V>>.div(other: Field<V, V2>): Field<T, V2>

Combines Kotlin properties into a path usable to point to any item in an array.

doesNotExist

open fun Field<T, *>.doesNotExist()

Matches documents that do not contain the specified field. Documents where the field if null are not matched.

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

collection.find {
    User::age.doesNotExist()
}
External resources

See also

open fun KProperty1<T, *>.doesNotExist()

Matches documents that do not contain the specified field. Documents where the field if null are not matched.

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

collection.find {
    User::age.doesNotExist()
}
External resources

See also

eq

open infix fun <V> Field<T, V>.eq(value: V)

Matches documents where the value of a field equals the value.

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

collection.find {
    User::name eq "foo"
}
External resources
open infix fun <V> KProperty1<T, V>.eq(value: V)

Matches documents where the value of a field equals the value.

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

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

eqNotNull

open infix fun <V> Field<T, V>.eqNotNull(value: V?)

Matches documents where the value of a field equals value.

If value is null, the operator is not added (all documents are matched).

Example

This operator is useful to simplify searches when the criteria are optional. For example, instead of writing:

collection.find {
    if (criteria.name != null)
        User::name eq criteria.name
}

this operator can be used instead:

collection.find {
    User::name eqNotNull criteria.name
}
External resources

See also

open infix fun <V> KProperty1<T, V>.eqNotNull(value: V?)

Matches documents where the value of a field equals value.

If value is null, the operator is not added (all documents are matched).

Example

This operator is useful to simplify searches when the criteria are optional. For example, instead of writing:

collection.find {
    if (criteria.name != null)
        User::name eq criteria.name
}

this operator can be used instead:

collection.find {
    User::name eqNotNull criteria.name
}
External resources

See also

exists

open fun Field<T, *>.exists()

Matches documents that contain the specified field, including values where the field value is null.

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

collection.find {
    User::age.exists()
}
External resources

See also

open fun KProperty1<T, *>.exists()

Matches documents that contain the specified field, including values where the field value is null.

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

collection.find {
    User::age.exists()
}
External resources

See also

expr

abstract fun expr(block: AggregationOperators.() -> Value<T & Any, Boolean>)

Enables the usage of aggregation values within a regular query.

Aggregation values are much more powerful than regular query operators (for example, it is possible to compare two fields of the same document). However, the way they are written is quite different, and the way they are evaluated by MongoDB is quite different again. Before using aggregation values, be sure to read AggregationOperators.

Example
class Product(
    val name: String,
    val creationDate: Instant,
    val releaseDate: Instant,
)

val anomalies = products.find {
    expr {
        of(Product::creationDate) gt of(Product::releaseDate)
    }
}
External resources

freeze

@LowLevelApi



abstract override fun freeze()

Makes this expression immutable.

get

open operator fun <Root, Type> KProperty1<Root, Collection<Type>>.get(index: Int): Field<Root, Type>

Refers to a specific item in an array, by its index.

open operator fun <Root, Type> KProperty1<Root, Map<String, Type>>.get(index: String): Field<Root, Type>

Refers to a specific item in a map, by its name.

open operator fun <Root, Type> Field<Root, Collection<Type>>.get(index: Int): Field<Root, Type>

Refers to a specific item in an array, by its index.

open operator fun <Root, Type> Field<Root, Map<String, Type>>.get(key: String): Field<Root, Type>

Refers to a specific item in a map, by its name.

gt

open infix fun <V> Field<T, V>.gt(value: V)

Selects documents for which this field has a value strictly greater than value.

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

collection.find {
    User::age gt 18
}
External resources

See also

open infix fun <V> KProperty1<T, V>.gt(value: V)

Selects documents for which this field has a value strictly greater than value.

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

collection.find {
    User::age gt 18
}
External resources

See also

gte

open infix fun <V> Field<T, V>.gte(value: V)

Selects documents for which this field has a value greater or equal to value.

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

collection.find {
    User::age gte 18
}
External resources

See also

open infix fun <V> KProperty1<T, V>.gte(value: V)

Selects documents for which this field has a value greater or equal to value.

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

collection.find {
    User::age gte 18
}
External resources

See also

gteNotNull

open infix fun <V> Field<T, V>.gteNotNull(value: V?)

Selects documents for which this field has a value greater or equal to value.

If value is null, the operator is not added (all elements are matched).

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

collection.find {
    User::age gteNotNull 10
}
External resources

See also

open infix fun <V> KProperty1<T, V>.gteNotNull(value: V?)

Selects documents for which this field has a value greater or equal to value.

If value is null, the operator is not added (all elements are matched).

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

collection.find {
    User::age gteNotNull 10
}
External resources

See also

gtNotNull

open infix fun <V> Field<T, V>.gtNotNull(value: V?)

Selects documents for which this field has a value strictly greater than value.

If value is null, the operator is not added (all elements are matched).

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

collection.find {
    User::age gtNotNull 10
}
External resources

See also

open infix fun <V> KProperty1<T, V>.gtNotNull(value: V?)

Selects documents for which this field has a value strictly greater than value.

If value is null, the operator is not added (all elements are matched).

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

collection.find {
    User::age gtNotNull 10
}
External resources

See also

hasType

open infix fun Field<T, *>.hasType(type: BsonType)

Selects documents where the value of the field is an instance of the specified BSON type.

Querying by data type is useful when dealing with highly unstructured data where data types are not predictable.

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

collection.find {
    User::age hasType BsonType.STRING
}
External resources

See also

open infix fun KProperty1<T, *>.hasType(type: BsonType)

Selects documents where the value of the field is an instance of the specified BSON type.

Querying by data type is useful when dealing with highly unstructured data where data types are not predictable.

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

collection.find {
    User::age hasType BsonType.STRING
}
External resources

See also

invoke

abstract operator fun <V> Field<T, V>.invoke(block: FilterQueryPredicate<V>.() -> Unit)

Targets a single field to execute a targeted predicate.

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

collection.find {
    User::name {
        eq("foo")
    }
}

Note that many operators available this way have a convenience function directly in this class to shorten this. For this example, see eq:

collection.find {
    User::name eq "foo"
}
open operator fun <V> KProperty1<T, V>.invoke(block: FilterQueryPredicate<V>.() -> Unit)

Targets a single field to execute a targeted predicate.

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

collection.find {
    User::name {
        eq("foo")
    }
}

Note that many operators available this way have a convenience function directly in this class to shorten this. For this example, see eq:

collection.find {
    User::name eq "foo"
}

isEmpty

open fun Field<T, Collection<*>>.isEmpty()

Matches documents in which an array is empty or absent.

Example

Return all users that have no grades (either an empty array, or the grades field is absent):

class User(
    val name: String?,
    val grades: List<Int>
)

collection.find {
    User::grades.isEmpty()
}

See also

open fun KProperty1<T, Collection<*>>.isEmpty()

Matches documents in which an array is empty or absent.

Example

Return all users that have no grades (either an empty array, or the grades field is absent):

class User(
    val name: String?,
    val grades: List<Int>
)

collection.find {
    User::grades.isEmpty()
}

See also

isIn

open infix fun <V : Comparable<V>> Field<T, V?>.isIn(range: ClosedRange<V>)

Selects documents in which this field has a value included in range.

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

collection.find {
    User::age isIn (25..50)
}

See also

open infix fun <V : Comparable<V>> KProperty1<T, V?>.isIn(range: ClosedRange<V>)

Selects documents in which this field has a value included in range.

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

collection.find {
    User::age isIn (25..50)
}

See also

open infix fun <V : Comparable<V>> Field<T, V?>.isIn(range: OpenEndRange<V>)

Selects documents in which this field has a value included in range.

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

collection.find {
    User::age isIn (25..<50)
}

See also

open infix fun <V : Comparable<V>> KProperty1<T, V?>.isIn(range: OpenEndRange<V>)

Selects documents in which this field has a value included in range.

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

collection.find {
    User::age isIn (25..<50)
}

See also

@JvmName
(name = "isInSimple")open infix fun <V : Comparable<V>, R : ClosedRange<V>, OpenEndRange<V>> Field<T, V?>.isIn(range: R)

Selects documents in which this field has a value included in range.

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

collection.find {
    User::age isIn (25..50)
}

See also

@JvmName
(name = "isInSimple")open infix fun <V : Comparable<V>, R : ClosedRange<V>, OpenEndRange<V>> KProperty1<T, V?>.isIn(range: R)

Selects documents in which this field has a value included in range.

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

collection.find {
    User::age isIn (25..50)
}

See also

isMapEmpty

open fun Field<T, Map<String, *>>.isMapEmpty()

Matches documents in which a map is empty or absent.

Example

Return all users that have no grades (either an empty map, or the grades field is absent):

class User(
    val name: String?,
    val grades: Map<String, Int>
)

collection.find {
    User::grades.isMapEmpty()
}

See also

open fun KProperty1<T, Map<String, *>>.isMapEmpty()

Matches documents in which a map is empty or absent.

Example

Return all users that have no grades (either an empty map, or the grades field is absent):

class User(
    val name: String?,
    val grades: Map<String, Int>
)

collection.find {
    User::grades.isMapEmpty()
}

See also

isMapNotEmpty

open fun Field<T, Map<String, *>>.isMapNotEmpty()

Matches documents in which a map is not empty.

Example

Return all users that have one or more grades.

class User(
    val name: String?,
    val grades: Map<String, Int>
)

collection.find {
    User::grades.isMapNotEmpty()
}

See also

open fun KProperty1<T, Map<String, *>>.isMapNotEmpty()

Matches documents in which a map is not empty.

Example

Return all users that have one or more grades.

class User(
    val name: String?,
    val grades: Map<String, Int>
)

collection.find {
    User::grades.isMapNotEmpty()
}

See also

isNotEmpty

open fun Field<T, Collection<*>>.isNotEmpty()

Matches documents in which an array is not empty.

Example

Return all users that have one or more grades.

class User(
    val name: String?,
    val grades: List<Int>
)

collection.find {
    User::grades.isNotEmpty()
}

See also

open fun KProperty1<T, Collection<*>>.isNotEmpty()

Matches documents in which an array is not empty.

Example

Return all users that have one or more grades.

class User(
    val name: String?,
    val grades: List<Int>
)

collection.find {
    User::grades.isNotEmpty()
}

See also

isNotNull

open fun Field<T, *>.isNotNull()

Selects documents for which the field is not null.

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

collection.find {
    User::age.isNotNull()
}
External resources

See also

open fun KProperty1<T, *>.isNotNull()

Selects documents for which the field is not null.

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

collection.find {
    User::age.isNotNull()
}
External resources

See also

isNotOneOf

open fun <V> Field<T, V>.isNotOneOf(values: List<V>)

Selects documents for which this field is not equal to any of the given values.

This operator will also select documents for which the field doesn't exist.

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

collection.find {
    User::name.isNotOneOf(listOf("Alfred", "Arthur"))
}
External resources

See also

open fun <V> KProperty1<T, V>.isNotOneOf(values: List<V>)

Selects documents for which this field is not equal to any of the given values.

This operator will also select documents for which the field doesn't exist.

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

collection.find {
    User::name.isNotOneOf(listOf("Alfred", "Arthur"))
}
External resources

See also

open fun <V> Field<T, V>.isNotOneOf(vararg values: V)

Selects documents for which this field is not equal to any of the given values.

This operator will also select documents for which the field doesn't exist.

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

collection.find {
    User::name.isNotOneOf("Alfred", "Arthur")
}
External resources

See also

open fun <V> KProperty1<T, V>.isNotOneOf(vararg values: V)

Selects documents for which this field is not equal to any of the given values.

This operator will also select documents for which the field doesn't exist.

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

collection.find {
    User::name.isNotOneOf("Alfred", "Arthur")
}
External resources

See also

isNotUndefined

open fun Field<T, *>.isNotUndefined()
Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Selects documents for which the field is not undefined.

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

collection.find {
    User::age.isNotUndefined()
}
External resources

See also

open fun KProperty1<T, *>.isNotUndefined()
Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Selects documents for which the field is not undefined.

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

collection.find {
    User::age.isNotUndefined()
}
External resources

See also

isNull

open fun Field<T, *>.isNull()

Selects documents for which the field is null.

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

collection.find {
    User::age.isNull()
}
External resources

See also

open fun KProperty1<T, *>.isNull()

Selects documents for which the field is null.

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

collection.find {
    User::age.isNull()
}
External resources

See also

isOneOf

open fun <V> Field<T, V>.isOneOf(values: List<V>)

Selects documents for which this field is equal to one of the given values.

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

collection.find {
    User::name.isOneOf(listOf("Alfred", "Arthur"))
}
External resources

See also

open fun <V> KProperty1<T, V>.isOneOf(values: List<V>)

Selects documents for which this field is equal to one of the given values.

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

collection.find {
    User::name.isOneOf(listOf("Alfred", "Arthur"))
}
External resources

See also

open fun <V> Field<T, V>.isOneOf(vararg values: V)

Selects documents for which this field is equal to one of the given values.

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

collection.find {
    User::name.isOneOf("Alfred", "Arthur")
}
External resources

See also

open fun <V> KProperty1<T, V>.isOneOf(vararg values: V)

Selects documents for which this field is equal to one of the given values.

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

collection.find {
    User::name.isOneOf("Alfred", "Arthur")
}
External resources

See also

isUndefined

open fun Field<T, *>.isUndefined()
Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Selects documents for which the field is undefined.

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

collection.find {
    User::age.isUndefined()
}
External resources

See also

open fun KProperty1<T, *>.isUndefined()
Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Selects documents for which the field is undefined.

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

collection.find {
    User::age.isUndefined()
}
External resources

See also

lt

open infix fun <V> Field<T, V>.lt(value: V)

Selects documents for which this field has a value strictly lesser than value.

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

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

See also

open infix fun <V> KProperty1<T, V>.lt(value: V)

Selects documents for which this field has a value strictly lesser than value.

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

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

See also

lte

open infix fun <V> Field<T, V>.lte(value: V)

Selects documents for which this field has a value lesser or equal to value.

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

collection.find {
    User::age lte 18
}
External resources

See also

open infix fun <V> KProperty1<T, V>.lte(value: V)

Selects documents for which this field has a value lesser or equal to value.

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

collection.find {
    User::age lte 18
}
External resources

See also

lteNotNull

open infix fun <V> Field<T, V>.lteNotNull(value: V?)

Selects documents for which this field has a value lesser or equal to value.

If value is null, the operator is not added (all elements are matched).

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

collection.find {
    User::age lteNotNull 10
}
External resources

See also

open infix fun <V> KProperty1<T, V>.lteNotNull(value: V?)

Selects documents for which this field has a value lesser or equal to value.

If value is null, the operator is not added (all elements are matched).

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

collection.find {
    User::age lteNotNull 10
}
External resources

See also

ltNotNull

open infix fun <V> Field<T, V>.ltNotNull(value: V?)

Selects documents for which this field has a value strictly lesser than value.

If value is null, the operator is not added (all elements are matched).

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

collection.find {
    User::age ltNotNull 10
}
External resources

See also

open infix fun <V> KProperty1<T, V>.ltNotNull(value: V?)

Selects documents for which this field has a value strictly lesser than value.

If value is null, the operator is not added (all elements are matched).

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

collection.find {
    User::age ltNotNull 10
}
External resources

See also

ne

open infix fun <V> Field<T, V>.ne(value: V)

Matches documents where the value of a field does not equal the value.

The result includes documents which do not contain the specified field.

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

collection.find {
    User::name ne "foo"
}
External resources

See also

open infix fun <V> KProperty1<T, V>.ne(value: V)

Matches documents where the value of a field does not equal the value.

The result includes documents which do not contain the specified field.

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

collection.find {
    User::name ne "foo"
}
External resources

See also

nor

abstract fun nor(block: FilterQuery<T>.() -> Unit)

Performs a logical NOR operation on one or more expressions, and selects the documents that do not satisfy any of the expressions.

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

collection.find {
    nor {
        User::name eq "foo"
        User::name eq "bar"
        User::age eq 18
    }
}
External resources

See also

not

open infix fun <V> Field<T, V>.not(expression: FilterQueryPredicate<V>.() -> Unit)

Performs a logical NOT operation on the specified expression and selects the documents that do not match the expression. This includes the elements that do not contain the field.

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

collection.find {
    User::age not {
        hasType(BsonType.STRING)
    }
}
External resources
open infix fun <V> KProperty1<T, V>.not(expression: FilterQueryPredicate<V>.() -> Unit)

Performs a logical NOT operation on the specified expression and selects the documents that do not match the expression. This includes the elements that do not contain the field.

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

collection.find {
    User::age not {
        hasType(BsonType.STRING)
    }
}
External resources

or

abstract fun or(block: FilterQuery<T>.() -> Unit)

Performs a logical OR operation on one or more expressions, and selects the documents that satisfy at least one of the expressions.

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

collection.find {
    or {
        User::name eq "foo"
        User::name eq "bar"
        User::age eq 18
    }
}
External resources

See also

regex

open fun Field<T, String?>.regex(
    pattern: String, 
    caseInsensitive: Boolean = false, 
    dotAll: Boolean = false, 
    extended: Boolean = false, 
    matchEachLine: Boolean = false
)

Matches documents where the field corresponds to a given regex expression.

Example
class User(
    val name: String,
)

collection.find {
    User::name.regex("John .*")
}
Indexing

If possible, prefer using a "^" prefix. For example, if we know that a pattern will only be present at the start of a string, "^foo" will use indexes, whereas "foo" will not.

Avoid using .* at the start and end of a pattern. "foo" is identical to "foo.*", but the former can use indexes and the latter cannot.

External resources

Parameters

  • caseInsensitive: If true, the result is matched even if its case doesn't match. Note that this also disables index usage (even case-insensitive indexes) and ignores collation.

  • dotAll: If true, the dot character (.) can match newlines.

  • extended: If true, whitespace (except in character classes) is ignored, and segments starting from an unescaped pound (#) until a newline are ignored, similarly to a Python comment.

User::name.regex(
    pattern = """
        abc # This is a comment, it's not part of the pattern
        123
    """.trimIndent(),
    extended = true,
)

which is identical to the non-extended pattern "abc123".

  • matchEachLine: If true, the special characters ^ and $ match the beginning and end of each line, instead of matching the beginning and end of the entire string. Therefore, "^S" will match "First line\nSecond line", which would not match otherwise.
open fun KProperty1<T, String?>.regex(
    pattern: String, 
    caseInsensitive: Boolean = false, 
    dotAll: Boolean = false, 
    extended: Boolean = false, 
    matchEachLine: Boolean = false
)

Matches documents where the field corresponds to a given regex expression.

Example
class User(
    val name: String,
)

collection.find {
    User::name.regex("John .*")
}
Indexing

If possible, prefer using a "^" prefix. For example, if we know that a pattern will only be present at the start of a string, "^foo" will use indexes, whereas "foo" will not.

Avoid using .* at the start and end of a pattern. "foo" is identical to "foo.*", but the former can use indexes and the latter cannot.

External resources

Parameters

  • caseInsensitive: If true, the result is matched even if its case doesn't match. Note that this also disables index usage (even case-insensitive indexes) and ignores collation.

  • dotAll: If true, the dot character (.) can match newlines.

  • extended: If true, whitespace (except in character classes) is ignored, and segments starting from an unescaped pound (#) until a newline are ignored, similarly to a Python comment.

User::name.regex(
    pattern = """
        abc # This is a comment, it's not part of the pattern
        123
    """.trimIndent(),
    extended = true,
)

which is identical to the non-extended pattern "abc123".

  • matchEachLine: If true, the special characters ^ and $ match the beginning and end of each line, instead of matching the beginning and end of the entire string. Therefore, "^S" will match "First line\nSecond line", which would not match otherwise.

simplify

@LowLevelApi



abstract fun simplify(): BsonNode?

Returns a simplified (but equivalent) expression to the current expression.

size

abstract infix fun Field<T, Collection<*>>.size(size: Int)

Selects documents where the value of a field is an array of size size (exactly).

This operator cannot accept a range of values. To select documents based on fields with different numbers of elements, create a counter field that you increment when you add elements to a field.

Queries cannot use indexes for this portion of the query, but other parts of the query may use indexes if applicable.

Example
class User(
    val grades: List<Int>,
)

collection.find {
    User::grades size 3
}
External resources
open infix fun KProperty1<T, Collection<*>>.size(size: Int)

Selects documents where the value of a field is an array of size size (exactly).

This operator cannot accept a range of values. To select documents based on fields with different numbers of elements, create a counter field that you increment when you add elements to a field.

Queries cannot use indexes for this portion of the query, but other parts of the query may use indexes if applicable.

Example
class User(
    val grades: List<Int>,
)

collection.find {
    User::grades size 3
}
External resources

toBson

@LowLevelApi



open fun toBson(): Bson

Writes the result of simplifying to a new BSON document.

toString

abstract override fun toString(): String

JSON representation of this expression.

unsafe

open infix fun <Root, Child> KProperty1<Root, *>.unsafe(child: String): Field<Root, Child>

Refers to a field child of the current field, with no compile-time safety.

open infix fun <Root, Child> KProperty1<Root, *>.unsafe(child: KProperty1<*, Child>): Field<Root, Child>

Refers to a field child of the current field, without checking that it is a field available on the current object.

open infix fun <Root, Child> KProperty1<Root, *>.unsafe(child: Field<*, Child>): Field<Root, Child>

Refers to a field child of the current field, without checking that it is a field available on the current object.

open infix fun <Root, Child> Field<Root, *>.unsafe(child: KProperty1<*, Child>): Field<Root, Child>

Refers to a field child of the current field, without checking that it is a field available on the current object.

open infix fun <Root, Child> Field<Root, *>.unsafe(child: Field<*, Child>): Field<Root, Child>

Refers to a field child of the current field, without checking that it is a field available on the current object.

open infix fun <Root, Type, Child> Field<Root, Type>.unsafe(child: String): Field<Root, Child>

Refers to a field child of the current field, with no compile-time safety.

writeTo

@LowLevelApi



abstract override fun writeTo(writer: BsonFieldWriter)

Writes the result of simplifying this expression into writer.