Version 3, last updated by eltimn at 15 Feb 13:30 UTC

Lift must have at least one MongoDB defined. If you only need one database, then you can use the DefaultMongoIdentifier.

Define a default db:

import com.mongodb.Mongo
import net.liftweb.mongodb.{DefaultMongoIdentifier, MongoDB}

MongoDB.defineDb(DefaultMongoIdentifier, new Mongo, "test")

If you need more than one database, you’ll need to define a MongoIdentifier for each one:

import com.mongodb.Mongo
import net.liftweb.mongodb.{MongoIdentifier, MongoDB}

object MainDb extends MongoIdentifier {
  val jndiName = "main"
}

MongoDB.defineDb(MainDb, new Mongo, "test")

You can pass in MongoOptions in the following manner:

import com.mongodb.{Mongo, MongoOptions, ServerAddress}
import net.liftweb.mongodb.{DefaultMongoIdentifier, MongoDB}

val srvr = new ServerAddress("127.0.0.1", 27017)
val mo = new MongoOptions
mo.socketTimeout = 10

MongoDB.defineDb(DefaultMongoIdentifier, new Mongo(srvr, mo), "test")

If you use authentication, you can define your db this way:

import com.mongodb.Mongo
import net.liftweb.mongodb.{DefaultMongoIdentifier, MongoDB}

MongoDB.defineDbAuth(DefaultMongoIdentifier, new Mongo, "test", "db_user", "db_pwd")

For Replica Sets:
import com.mongodb.{Mongo, MongoOptions, ServerAddress}
import net.liftweb.mongodb.{DefaultMongoIdentifier, MongoDB}
import scala.collection.JavaConversions._

val srvr1 = new ServerAddress("127.0.0.1", 27017)
val srvr2 = new ServerAddress("127.0.0.1", 27018)
val srvr3 = new ServerAddress("127.0.0.1", 27019)
val srvrs = srvr1 :: srvr2 :: srvr3 :: Nil

MongoDB.defineDb(DefaultMongoIdentifier, new Mongo(srvrs), "test")

Initialization
You must initialize Mongo in Boot, but you can put your code anywhere you’d like. I put a MongoConfig object in the model package and call it’s init function from Boot.

myapp/model/MongoConfig.scala

package myapp.model

import net.liftweb._
import mongodb._
import util.Props
import com.mongodb.{Mongo, ServerAddress}

object MongoConfig {
  def init: Unit = {
    val srvr = new ServerAddress(
       Props.get("mongo.host", "127.0.0.1"),
       Props.getInt("mongo.port", 27017)
    )
    MongoDB.defineDb(DefaultMongoIdentifier, new Mongo(srvr), "myapp")
  }
}

bootstrap/liftweb/Boot.scala

package bootstrap.liftweb

import net.liftweb._
import myapp.model.MongoConfig

class Boot {
  def boot: Unit = {
    // make sure you call this before trying to use any of your Mongo model classes.
    MongoConfig.init
  }
}

For more info see the api docs for the Mongo class

Note: If you look in the source code, you’ll see classes such as MongoAddress and MongoHost. These were created long ago, before ServerAddress existed. These are not really needed anymore, as you can now just pass in a Mongo instance to MongoDB.defineDb.