-
Notifications
You must be signed in to change notification settings - Fork 0
MongoDB Usage
virtualWinter edited this page Aug 30, 2025
·
2 revisions
This guide explains how to use the MongoDB features of the Storage library.
First, create an instance of the Mongo class. You can do this in two ways:
Mongo mongo = new Mongo("mongodb://user:password@localhost:27017/my-database", "my-database");
mongo.init();
mongo.start();Mongo mongo = new Mongo("localhost", 27017, "user", "password", "my-database");
mongo.init();
mongo.start();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
}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);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.
© 2025 CatMC Network