Chapter 8. MongoDB Persistence with Record
This chapter gives recipes for making use of MongoDB in your Lift application. Many of the code examples in this chapter can be found at https://github.com/LiftCookbook/cookbook_mongo.
Connecting to a MongoDB Database
Problem
You want to connect to a MongoDB database.
Solution
Add the Lift MongoDB dependencies to your build and configure a connection using net.liftweb.mongodb and com.mongodb.
In build.sbt, add the following to libraryDependencies:
"net.liftweb"%%"lift-mongodb-record"%liftVersion
In Boot.scala, add:
importcom.mongodb.{ServerAddress,Mongo}importnet.liftweb.mongodb.{MongoDB,DefaultMongoIdentifier}valserver=newServerAddress("127.0.0.1",27017)MongoDB.defineDb(DefaultMongoIdentifier,newMongo(server),"mydb")
This will give you a connection to a local MongoDB database called
mydb.
Discussion
If your database needs authentication, use MongoDB.defineDbAuth:
MongoDB.defineDbAuth(DefaultMongoIdentifier,newMongo(server),"mydb","username","password")
Some cloud services will give you a URL to connect to, such as mongodb://alex.mongohq.com:10050/fglvBskrsdsdsDaGNs1. In this case, the host and the port make up the first part, and the database name is the part after the /.
If you need to turn a URL like this into a connection, you can do so by
using java.net.URI to parse the URL and make a connection:
objectMongoUrl{defdefineDb(id:MongoIdentifier,url:String){valuri=newURI(url)valdb=uri.getPathdrop1valserver
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access