addEachToSet

open fun <V> Field<T, Collection<V>>.addEachToSet(values: Iterable<V>, type: KType)(source)
infix inline fun <V> Field<T, Collection<V>>.addEachToSet(values: Iterable<V>)(source)
infix inline fun <V> KProperty1<T, Collection<V>>.addEachToSet(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 addEachToSet 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