addToSet

abstract fun <V> Field<T, Collection<V>>.addToSet(value: V, type: KType)(source)
infix inline fun <V> Field<T, Collection<V>>.addToSet(value: V)(source)
infix inline 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