Skip to content

Commit

Permalink
Changed: Optimized MongoStorage
Browse files Browse the repository at this point in the history
Signed-off-by: DevDrizzy <[email protected]>
  • Loading branch information
DevDrizzy committed Sep 5, 2024
1 parent 550afda commit 28cbaa4
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
20 changes: 8 additions & 12 deletions src/main/java/xyz/refinedev/api/storage/MongoStorage.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.ReplaceOptions;

import com.mongodb.client.model.Updates;
import org.bson.Document;
import org.bson.conversions.Bson;

Expand All @@ -32,10 +33,12 @@ public class MongoStorage<V> {

private final MongoCollection<Document> collection;
private final Gson gson;
private final Type typeToken;

public MongoStorage(MongoCollection<Document> collection, Gson gson) {
this.collection = collection;
this.gson = gson;
this.typeToken = new TypeToken<V>() {}.getType();
}

public CompletableFuture<List<V>> fetchAllEntries() {
Expand All @@ -45,7 +48,6 @@ public CompletableFuture<List<V>> fetchAllEntries() {
if (document == null) {
continue;
}
Type typeToken = new TypeToken<V>() {}.getType();
found.add(this.gson.fromJson(document.toJson(), typeToken));
}
return found;
Expand Down Expand Up @@ -117,19 +119,13 @@ public void deleteData(UUID key) {
* @param key {@link String key}
* @return {@link Integer amount of deleted documents}
*/
public CompletableFuture<Integer> deleteKeyInAll(String key) {
public CompletableFuture<Long> deleteKeyInAll(String key) {
return CompletableFuture.supplyAsync(() -> {
int deleteCount = 0;
for ( Document document : collection.find() ) {
if (document == null) continue;
// Unset the key
Bson combinedUpdate = Updates.unset(key);

if (document.get(key) != null) {
document.remove(key);
deleteCount++;
}
collection.replaceOne(Filters.eq("_id", document.get("_id")), document);
}
return deleteCount;
// Apply the updates to all documents in the collection
return collection.updateMany(new Document(), combinedUpdate).getModifiedCount(); // new Document() is an empty filter, meaning "all documents";
});
}
}
1 change: 0 additions & 1 deletion src/main/java/xyz/refinedev/api/storage/YamlStorage.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package xyz.refinedev.api.storage;

import org.apache.commons.io.Charsets;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

Expand Down

0 comments on commit 28cbaa4

Please sign in to comment.