Skip to content

MongoDB Usage

virtualWinter edited this page Aug 30, 2025 · 2 revisions

MongoDB Usage

This guide explains how to use the MongoDB features of the Storage library.

1. Initialization

First, create an instance of the Mongo class. You can do this in two ways:

With a Connection String

Mongo mongo = new Mongo("mongodb://user:password@localhost:27017/my-database", "my-database");
mongo.init();
mongo.start();

With Credentials

Mongo mongo = new Mongo("localhost", 27017, "user", "password", "my-database");
mongo.init();
mongo.start();

2. Defining a Document

Create a Plain Old Java Object (POJO) and annotate it with @Document to map it to a MongoDB collection. You can also use @Id, @Field, and @Transient to customize the mapping.

@Document("users")
public class User {

    @Id
    private ObjectId id;

    @Field("user_name")
    private String userName;

    private String password;

    @Transient
    private String temporaryToken;

    // Getters and setters
}

3. Creating an Index

You can automatically create indexes for your collections by annotating fields with @Indexed.

@Document("users")
public class User {
    // ...

    @Indexed(unique = true)
    private String email;

    // ...
}

Then, call the createIndexes method:

mongo.createIndexes(User.class);

4. Accessing a Collection

To get a MongoCollection instance for your document class, use the getCollection method:

MongoCollection<User> userCollection = mongo.getCollection(User.class);

You can then use the collection to perform standard MongoDB operations.

Clone this wiki locally