Getting Started
A library for easy usage of the mongo-scala-driver.
Dependency Setup
Support Scala 2.12 and Scala 2.13.
scala
libraryDependencies += "dev.mongocamp" %% "mongodb-driver" % "2.8.2.snapshot"
scala
def ivyDeps = Agg(
ivy"dev.mongocamp:::mongodb-driver:2.8.2.snapshot"
)
xml
<dependency>
<groupId>dev.mongocamp</groupId>
<artifactId>mongodb-driver_2.13</artifactId>
<version>2.8.2.snapshot</version>
</dependency>
groovy
dependencies {
implementation "dev.mongocamp:mongodb-driver_2.13:2.8.2.snapshot"
}
Features:
- Easy Database Config with provider and MongoConfig
- Implement the DAO Pattern for simple MongoDB usage (MongoDAO)
- GridFS support (GridFSDAO)
- Reactive Streams support (Usage in mongocamp)
- Enhanced BSON conversion support (Bson)
- Relationships
Example: Model
Create custom model classes.
scala
case class Student(_id: Long, name: String, scores: List[Score], image: Option[ObjectId])
case class Score(score: Double, `type`: String)
case class Grade(_id: ObjectId, studentId: Long, classId: Long, scores: List[Score])
Example: Database
scala
package dev.mongocamp.driver.mongodb.test
import dev.mongocamp.driver.mongodb.database.DatabaseProvider
import dev.mongocamp.driver.mongodb.model._
import dev.mongocamp.driver.mongodb.server.LocalServer
import dev.mongocamp.driver.mongodb.{GridFSDAO, MongoDAO}
import org.bson.codecs.configuration.CodecRegistries.{fromProviders, fromRegistries}
import org.bson.codecs.configuration.CodecRegistry
import org.mongodb.scala.bson.codecs.Macros._
object UniversityDatabase {
// create local test server (mongodb-java-server)
var LocalTestServer: LocalServer = _
// create codecs for custom classes
private val universityRegistry: CodecRegistry = fromProviders(classOf[Student], classOf[Score], classOf[Grade])
private val registry: CodecRegistry = fromRegistries(universityRegistry)
// create provider
val provider: DatabaseProvider = DatabaseProvider.fromPath(configPath = "unit.test.mongo.local", registry = registry)
// setup DAO objects with mongodb collection names
object StudentDAO extends MongoDAO[Student](provider, "university-students")
object GradeDAO extends MongoDAO[Book](provider, "university-grades")
object SudentImagesDAO extends GridFSDAO(provider, "university-images")
}