目次

Version 4, last updated by amoss at Jul 28 03:35 UTC

MongoDB Base and MongoDocument Library

Installation

SBT users

Add dependency to your project description:

val lift_mongo = "net.liftweb" % "lift-mongodb" % "2.0-XX"

Maven users

Add dependency to your pom:

   <dependency>
  <groupId>net.liftweb</groupId>
  <artifactId>lift-mongodb</artifactId>
  <version>2.0-XX</version>
</dependency>

Usage

Low Level Operations

These are mostly used by the other library classes, but can be used directly if needed. See DirectExamples.scala for examples.

Define a default db:

MongoDB.defineDb(DefaultMongoIdentifier, MongoAddress(MongoHost("localhost", 27017), "test_direct"))

Use the db:

MongoDB.use(DefaultMongoIdentifier) ( db => {
  val doc = new BasicDBObject
  doc.put("name", "MongoDB")
  doc.put("type", "database")
  doc.put("count", 1)
  val coll = db.getCollection("testCollection")
  // save the doc to the db
  coll.save(doc)
})

Use a collection:

MongoDB.useCollection(collectionName) ( coll => {
  val doc = new BasicDBObject
  doc.put("name", "MongoDB")
  doc.put("type", "database")
  doc.put("count", 1)
  // save the doc to the db
  coll.save(doc)
})

Use a single thread for all operations:

MongoDB.useSession ( db => {
  val coll = db.getCollection("testCollection") 
  val doc = new BasicDBObject 
  doc.put("name", "MongoSession") 
  doc.put("type", "db") 
  doc.put("count", 1) 
  coll.save(doc) 
  db.getLastError 
  ...
})

MongoDocument Library

These rely on the lift-json project, but it doesn’t have any dependencies itself. See DocumentExamples.scala for examples.

Note: All String fields are checked to see if it is a valid ObjectId. If it is then an actual ObjectId is saved in Mongo.

Define domain objects:

case class Address(street: String, city: String)
case class Child(name: String, age: Int, birthdate: Option[Date])
case class Person(_id: String, name: String, age: Int, address: Address, children: List[Child])
    extends MongoDocument[Person] {
  def meta = Person
}
object Person extends MongoDocumentMeta[Person] {
  override def mongoIdentifier = TestDBa
  override def collectionName = "mypersons"	
}

Create an instance:

def date(s: String) = Person.formats.dateFormat.parse(s).get
val p = Person(
  ObjectId.get.toString,
  "joe",
  27,
  Address("Bulevard", "Helsinki"),
  List(Child("Mary", 5, Some(date("2004-09-04T18:06:22.000Z"))), Child("Mazy", 3, None))
)

Save it:

p.save

Retrieve it:

val pFromDb = Person.find(p._id)

Delete it:

p.delete

Queries can be written using the lift-json DSL:

import net.liftweb.json.JsonDSL._
Person.findAll(("name" -> "joe") ~ ("age" -> 27))

You could also create your Mongo documents using the DSL:

import net.liftweb.json._
import net.liftweb.json.JsonAST.JObject
import net.liftweb.json.JsonDSL._
implicit val formats = DefaultFormats.lossless
val json = JsonParser.parse("""
{ "name": "joe",
	"children": [
		{
		  "name": "Mary",
		  "age": 5
		},
		{
		  "name": "Mazy",
		  "age": 3
		}
	]
}
""").asInstanceOf[JObject]
MongoDB.useCollection("myCollection")( coll => {
	coll.save(JObjectParser.parse(json))
})

MongoDB GridFS

MongoDB GridFS supports storage of arbitrary length files using a chunked storage approach, see here for more details: http://www.mongodb.org/display/DOCS/GridFS

Assuming you’ve defined a default MongoDB connection in your Lift app, you can store a file using GridFS:

import com.mongodb.gridfs._
import net.liftweb.mongodb._
MongoDB.use(DefaultMongoIdentifier) ( db => {
  val fs = new GridFS(db)
  val inputFile = fs.createFile(new java.io.File("/path/to/myfile"))
  inputFile.setContentType("text/plain")
  inputFile.setFilename("myfile")
  inputFile.save
})

GridFS files can be retrieved in a number of ways, see: http://api.mongodb.org/java/current/com/mongodb/gridfs/GridFS.html

For example by filename:

MongoDB.use(DefaultMongoIdentifier) ( db => {
  val fs = new GridFS(db)
  val foundFile = fs.findOne("myfile")
  foundFile.writeTo("/path/to/myfoundfile")
})