Data
MongoDB
Use a document database with the same entities and repositories.
MongoDB stores documents (JSON-like objects) in collections, instead of rows in tables. It suits data that is naturally nested or has varying shape: event logs, content, catalogues. In Kest it is a datastore plugin behind the same entity model as PostgreSQL and MySQL: the annotations, the repository interface, derived finders, relations, soft delete and pagination work the same way. Add orm-mongo and name a connection:
import(OrmModule.forRoot {
mongo("events", System.getenv("MONGO_URI"), database = "events")
})
@Entity("audit_log", connection = "events") // "audit_log" is the collection name
data class AuditEntry(
@Id @Generated val id: String? = null, // null when new; MongoDB's _id is generated
val actor: String,
val action: String,
@CreateDate val at: Instant? = null, // filled on insert
)
@Repository interface AuditRepository : CrudRepository<AuditEntry, String> {
fun findByActor(actor: String): List<AuditEntry> // derived finder: becomes a MongoDB query
fun findByActionOrderByAtDesc(action: String, page: Pageable): Page<AuditEntry>
}
@Injectable
class Audit(@InjectRepository(AuditEntry::class, "events") private val log: MongoRepository<AuditEntry>) {
fun record(actor: String, action: String) = log.save(AuditEntry(actor = actor, action = action))
}The same code against PostgreSQL would differ only in the connection line.
What maps how
@Idmaps to_id; a generatedStringid is an ObjectId-style value generated on the client.@Indexand@Uniquecreate MongoDB indexes; a duplicate write throwsDuplicateKeyException.@Versiongives optimistic locking.- Migrations create collections and indexes, see Migrations.
- Cursor and offset pagination, the typed query DSL and soft delete work as on SQL.
Differences you must know
- Transactions (
@Transactional) need a replica set, which is MongoDB's own rule. A single standalone server cannot do them. (The test setup starts a one-node replica set.) @Column(select/insert/update)flags and column transformers are SQL-only: MongoDB stores the converted value but ignores those three flags.- Relations to entities in another database work with batched loading (Overview). There are no joins: related data is loaded with extra queries, in batches.
SQL or MongoDB?
| Choose SQL (PostgreSQL) when | Choose MongoDB when |
|---|---|
| data is relational, you need joins and strict constraints | documents are self-contained and nested |
| money, orders, inventory: strong consistency across tables | high-volume logs/events, flexible shape |
| you want powerful reporting queries | you read a whole document at a time |
When unsure, start with PostgreSQL: it also stores JSON (@Column(type = "jsonb")) for the flexible parts.