addToSet

abstract infix fun <V> Field<T, Collection<V>>.addToSet(value: V)(source)
open infix fun <V> KProperty1<T, Collection<V>>.addToSet(value: V)(source)

Adds value at the end of the array, unless it is already present, in which case it does nothing.

MongoDB detects equality if the two documents are exactly identical. All the fields must be the same in the same order.

Example

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

collection.updateOne(
filter = {
User::name eq "Bob"
},
update = {
User::tokens addToSet "123456789"
}
)

This will add "123456789" to the user's tokens only if it isn't already present.

External resources


open infix fun <V> Field<T, Collection<V>>.addToSet(values: Iterable<V>)(source)
open infix fun <V> KProperty1<T, Collection<V>>.addToSet(values: Iterable<V>)(source)

Adds multiple values at the end of the array, unless they are already present.

Each value in values is treated independently. It if it is already present in the array, nothing happens. If it is absent from the array, it is added at the end.

MongoDB detects equality if the two documents are exactly identical. All the fields must be the same in the same order.

This is a convenience function for calling addToSet multiple times.

Example

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

collection.updateOne(
filter = {
User::name eq "Bob"
},
update = {
User::tokens addToSet listOf("123456789", "789456123")
}
)

This will add "123456789" and "789465123" to the user's tokens only if they aren't already present. If only one of them is present, the other is added.

External resources