Skip to content

MongoDB request DSLopensavvy.ktmongo.dsl.queryUpdateQueryselected

selected

open val <E> Field<T, Collection<E>>.selected: Field<T, E>

The positional operator: update an array item selected in the filter.

When we use any or anyValue in a filter to select an item, we can use this operator to update whichever item was selected.

Do not use this operator in an upsert.

Example

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

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

users.updateMany(
    filter = {
        User::pets.any / Pet::name eq "Bobby"
    },
    update = {
        User::pets.selected / Pet::age inc 1
    }
)

This example finds all users who have a pet named "Bobby", and increases its age by 1. Note that if the users have other pets, they are not impacted.

External resources

open val <E> KProperty1<T, Collection<E>>.selected: Field<T, E>

The positional operator: update an array item selected in the filter.

When we use any or anyValue in a filter to select an item, we can use this operator to update whichever item was selected.

Do not use this operator in an upsert.

Example

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

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

users.updateMany(
    filter = {
        User::pets.any / Pet::name eq "Bobby"
    },
    update = {
        User::pets.selected / Pet::age inc 1
    }
)

This example finds all users who have a pet named "Bobby", and increases its age by 1. Note that if the users have other pets, they are not impacted.

External resources