Skip to content

Commit

Permalink
resolves #251 add setValueOnInsert
Browse files Browse the repository at this point in the history
  • Loading branch information
zigzago committed Jan 30, 2021
1 parent c421503 commit 6b404d0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,16 @@ class FindOneAndModifyTypedTest : AllCategoriesKMongoBaseTest<Friend>() {

assertEquals(expected, r)
}

@Test
fun canUseSetValueOnInsert() {
val expected = ExposableFriend(ObjectId().toString(), "John")
val r = col.withDocumentClass<ExposableFriend>().findOneAndUpdate(
ExposableFriend::_id eq expected._id,
setValueOnInsert(expected),
findOneAndUpdateUpsert().returnDocument(ReturnDocument.AFTER)
)

assertEquals(expected, r)
}
}
18 changes: 17 additions & 1 deletion kmongo-property/src/main/kotlin/org/litote/kmongo/Updates.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import com.mongodb.client.model.UpdateOneModel
import com.mongodb.client.model.UpdateOptions
import com.mongodb.client.model.Updates
import org.bson.conversions.Bson
import org.litote.kmongo.util.KMongoUtil
import org.litote.kmongo.util.ObjectMappingConfiguration
import kotlin.internal.OnlyInputTypes
import kotlin.reflect.KProperty

Expand Down Expand Up @@ -101,11 +103,25 @@ fun <T> unset(property: KProperty<T>): Bson = Updates.unset(property.path())
fun <@OnlyInputTypes T> setOnInsert(property: KProperty<T?>, value: T): Bson =
Updates.setOnInsert(property.path(), value)

/**
* Creates an update that sets the the collection to the given value, but only if the update is an upsert that
* results in an insert of a document.
*
* @param value the value to insert
* @return the update
* @mongodb.driver.manual reference/operator/update/setOnInsert/ $setOnInsert
* @see UpdateOptions#upsert(boolean)
*/
fun setValueOnInsert(
value: Any
): Bson =
Updates.setOnInsert(KMongoUtil.filterIdToBson(value, !ObjectMappingConfiguration.serializeNull))

/**
* Creates an update that renames a field.
*
* @param property the property
* @param newFieldName the new property
* @param newProperty the new property
* @return the update
* @mongodb.driver.manual reference/operator/update/rename/ $rename
*/
Expand Down

0 comments on commit 6b404d0

Please sign in to comment.