Version 4, last updated by eltimn at July 22, 2011 16:20 UTC
MongoDocument Library
MongoDocument is a lightweight Object Document Mapper that uses case classes as model classes. It provides a way to convert, via JObjectParser, case classes to DBObjects and an API to save, update, and find them in the database.
This depends on the lift-json project, but it doesn’t have any dependencies itself. See DocumentExamples.scala for examples.
Define domain objects:
import net.liftweb._
import mongodb._
import org.bson.types.ObjectId
import java.util.Date
case class Address(street: String, city: String)
case class Child(name: String, age: Int, birthdate: Option[Date])
object Person extends MongoDocumentMeta[Person] {
override def collectionName = "mypersons"
override def formats = super.formats + new ObjectIdSerializer + new DateSerializer
}
case class Person(_id: ObjectId, name: String, age: Int, address: Address, children: List[Child])
extends MongoDocument[Person] {
def meta = Person
}
Create an instance:
def date(s: String) = Person.formats.dateFormat.parse(s).get
val p = Person(
ObjectId.get,
"joe",
27,
Address("Bulevard", "Helsinki"),
List(Child("Mary", 5, Some(date("2004-09-04T18:06:22.000Z"))), Child("Mazy", 3, None))
)Save it:
p.saveRetrieve it:
val pFromDb = Person.find(p._id)Delete it:
p.deleteQuerying and Updating
All of the methods that require a query (find, findAll, count, update) take either a DBObject or JObject as the query. This means you can either use the standard mongo-java-driver apis, or use the lift-json DSL to construct your queries.
JsonDSL example:
import net.liftweb.json.JsonDSL._
Person.findAll(("name" -> "joe") ~ ("age" -> 27))
QueryBuilder example:
import com.mongodb._
val qry = QueryBuilder.start("name").is("joe")
.put("age").is(27)
.get
Person.findAll(qry)