Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 87 additions & 52 deletions docs/optional-modules/mongodb.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,69 @@ description: MongoDB database integration for document-based storage.

# MongoDB

## Setup
The `pluginbase-mongo` module provides a thin wrapper around the MongoDB Java driver (v5.6.1, shaded and relocated) for use in Spigot plugins.

## Dependency

Add `pluginbase-mongo` as a dependency. The MongoDB driver is shaded into the module jar, so no additional runtime dependencies are needed.

```xml
<dependency>
<groupId>dev.demeng</groupId>
<artifactId>pluginbase-mongo</artifactId>
<version>1.36.1-SNAPSHOT</version>
</dependency>
```

## Credentials

`MongoCredentials` holds the connection URI and database name.

| Field | Type | Description |
|------------|----------|---------------------------------------------|
| `uri` | `String` | MongoDB connection URI (required, non-null) |
| `database` | `String` | Name of the default database (required, non-null) |

There are two ways to create credentials:

```java
import dev.demeng.pluginbase.mongo.Mongo;
import dev.demeng.pluginbase.mongo.MongoCredentials;

// Create credentials with connection URI
// From explicit values
MongoCredentials credentials = MongoCredentials.of(
"mongodb://username:password@localhost:27017",
"minecraft"
);

// Or simple localhost connection
// From a Bukkit ConfigurationSection (keys: "uri", "database")
MongoCredentials credentials = MongoCredentials.of(
"mongodb://localhost:27017",
"minecraft"
getConfig().getConfigurationSection("mongo")
);
```

The `ConfigurationSection` overload reads `uri` (default `mongodb://localhost:27017`) and `database` (default `minecraft`).

## Creating a Connection

Pass credentials to the `Mongo` constructor. This immediately opens a connection and selects the default database.

```java
import dev.demeng.pluginbase.mongo.Mongo;

// Create Mongo instance
Mongo mongo = new Mongo(credentials);
```

## API Reference

`Mongo` implements `IMongo`, which extends `Terminable`.

| Method | Return Type | Description |
|--------------------------------|-----------------|------------------------------------------------|
| `getClient()` | `MongoClient` | The underlying MongoDB client instance |
| `getDatabase()` | `MongoDatabase` | The default database specified in credentials |
| `getDatabase(String name)` | `MongoDatabase` | A database by name from the same client |
| `close()` | `void` | Closes the client connection |

## Basic Operations

### Insert Document
Expand Down Expand Up @@ -100,6 +141,41 @@ players.updateOne(
players.deleteOne(Filters.eq("uuid", uuid.toString()));
```

## Queries

```java
import com.mongodb.client.model.Sorts;

// Top players by coins
List<Document> top = players
.find()
.sort(Sorts.descending("coins"))
.limit(10)
.into(new ArrayList<>());

// Players with level >= 10
List<Document> highLevel = players
.find(Filters.gte("level", 10))
.into(new ArrayList<>());

// Compound filter
List<Document> results = players
.find(Filters.and(
Filters.gte("level", 5),
Filters.lte("coins", 1000)
))
.into(new ArrayList<>());
```

## Indexes

```java
import com.mongodb.client.model.Indexes;

players.createIndex(Indexes.ascending("uuid"));
players.createIndex(Indexes.descending("coins"));
```

## Complete Example

```java
Expand All @@ -110,10 +186,9 @@ public class MyPlugin extends BasePlugin {

@Override
protected DependencyContainer configureDependencies() {
String uri = getConfig().getString("mongo.uri", "mongodb://localhost:27017");
String database = getConfig().getString("mongo.database", "minecraft");

MongoCredentials credentials = MongoCredentials.of(uri, database);
MongoCredentials credentials = MongoCredentials.of(
getConfig().getConfigurationSection("mongo")
);

this.mongo = new Mongo(credentials);
this.players = mongo.getDatabase().getCollection("players");
Expand All @@ -126,12 +201,10 @@ public class MyPlugin extends BasePlugin {

@Override
protected void enable() {
// Load on join
Events.subscribe(PlayerJoinEvent.class)
.handler(e -> loadPlayer(e.getPlayer()))
.bindWith(this);

// Save on quit
Events.subscribe(PlayerQuitEvent.class)
.handler(e -> savePlayer(e.getPlayer()))
.bindWith(this);
Expand All @@ -144,7 +217,6 @@ public class MyPlugin extends BasePlugin {
return players.find(Filters.eq("uuid", uuid.toString())).first();
}).thenApplySync(doc -> {
if (doc != null) {
// Apply loaded data
PlayerData data = new PlayerData(
uuid,
doc.getString("name"),
Expand All @@ -154,7 +226,6 @@ public class MyPlugin extends BasePlugin {
cache.put(uuid, data);
Text.tell(player, "&aData loaded!");
} else {
// Create new player
createPlayer(uuid, player.getName());
}
return doc;
Expand Down Expand Up @@ -196,42 +267,6 @@ public class MyPlugin extends BasePlugin {
}
```

## Queries

```java
import com.mongodb.client.model.Sorts;

// Top players by coins
List<Document> top = players
.find()
.sort(Sorts.descending("coins"))
.limit(10)
.into(new ArrayList<>());

// Players with level >= 10
List<Document> highLevel = players
.find(Filters.gte("level", 10))
.into(new ArrayList<>());

// Complex query
List<Document> results = players
.find(Filters.and(
Filters.gte("level", 5),
Filters.lte("coins", 1000)
))
.into(new ArrayList<>());
```

## Indexes

```java
import com.mongodb.client.model.Indexes;

// Create index for faster queries
players.createIndex(Indexes.ascending("uuid"));
players.createIndex(Indexes.descending("coins"));
```

## Cleanup

MongoDB connections are automatically closed when plugin disables (implements AutoCloseable).
`Mongo` implements `Terminable`. The connection is closed automatically when the plugin disables or when `close()` is called manually.
Loading
Loading