Skip to content

Commit

Permalink
Added LazyCollection#upsertOne(...)
Browse files Browse the repository at this point in the history
  • Loading branch information
srnyx committed Oct 19, 2023
1 parent f405c55 commit 4cb4ceb
Showing 1 changed file with 16 additions and 22 deletions.
38 changes: 16 additions & 22 deletions library/src/main/java/xyz/srnyx/lazylibrary/LazyCollection.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.UpdateOptions;

import org.bson.conversions.Bson;

Expand Down Expand Up @@ -84,6 +85,16 @@ public void updateOne(@NotNull Bson filter, @NotNull Bson update) {
collection.updateOne(filter, update);
}

/**
* Upserts a document in the collection
*
* @param filter the filter to apply
* @param update the update to apply
*/
public void upsertOne(@NotNull Bson filter, @NotNull Bson update) {
collection.updateOne(filter, update, new UpdateOptions().upsert(true));
}

/**
* Updates a document in the collection and returns the updated document
*
Expand All @@ -94,7 +105,8 @@ public void updateOne(@NotNull Bson filter, @NotNull Bson update) {
*/
@Nullable
public T findOneAndUpdate(@NotNull Bson filter, @NotNull Bson update) {
return collection.findOneAndUpdate(filter, update, getReturnAfter());
return collection.findOneAndUpdate(filter, update, new FindOneAndUpdateOptions()
.returnDocument(ReturnDocument.AFTER));
}

/**
Expand All @@ -107,7 +119,9 @@ public T findOneAndUpdate(@NotNull Bson filter, @NotNull Bson update) {
*/
@Nullable
public T findOneAndUpsert(@NotNull Bson filter, @NotNull Bson update) {
return collection.findOneAndUpdate(filter, update, getUpsert());
return collection.findOneAndUpdate(filter, update, new FindOneAndUpdateOptions()
.returnDocument(ReturnDocument.AFTER)
.upsert(true));
}

/**
Expand All @@ -128,24 +142,4 @@ public void deleteOne(@NotNull Bson filter) {
public void deleteOne(@NotNull String field, @Nullable Object value) {
deleteOne(Filters.eq(field, value));
}

/**
* Returns a new {@link FindOneAndUpdateOptions} instance with the {@link ReturnDocument#AFTER} option set
*
* @return the {@link FindOneAndUpdateOptions} instance
*/
@NotNull
private static FindOneAndUpdateOptions getReturnAfter() {
return new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER);
}

/**
* Returns a new {@link FindOneAndUpdateOptions} instance with the {@link ReturnDocument#AFTER} and {@link FindOneAndUpdateOptions#upsert(boolean)} options set
*
* @return the {@link FindOneAndUpdateOptions} instance
*/
@NotNull
private static FindOneAndUpdateOptions getUpsert() {
return getReturnAfter().upsert(true);
}
}

0 comments on commit 4cb4ceb

Please sign in to comment.