any

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

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>(source)
open val <V> KProperty1<T, Collection<V>>.any: Field<T, V>(source)

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