Scala操作MongoDB

首先创建SBT项目,首次创建的时候,由于需要下载SBT相关东西,花费的时间比较长,而且很有可能下载失败,要有耐心。

然后在build.sbt配置文件中引入MongoDB

libraryDependencies+="org.mongodb"%%"casbah"%"2.7.3"

对MongoDB的操作测试:

packagecom.leqienglish.controllers

importcom.mongodb.casbah.Imports._

importcom.mongodb.casbah.MongoDB

/**

* Created by zhuleqi on 2017/3/20.

*/

objectLQMongoClient {

defmain(args: Array[String]): Unit = {

this.insert()

this.query()

}

/**

* 创建MongoClient

*@return

*/

private defcreateMongoClient():MongoClient= {

MongoClient("localhost",27017)

}

private defgetDB(): MongoDB  ={

varclient =createMongoClient();

client.getDB("leqiEnglish")

}

private defgetCollection(name:String):MongoCollection={

valmongoDB =getDB();

mongoDB(name);

}

defquery(): Unit ={

valcoll =this.getCollection("test")

println("coll="+coll.size)

coll.find().foreach(println)

}

definsert(): Unit = {

valcoll =this.getCollection("test")

vardata =MongoDBObject("name"->"user1","id"->"001")

vardata02 =MongoDBObject("name"->"user2","id"->"002")

coll.insert(data);

coll.insert(data02);

}

}

你可能感兴趣的:(Scala操作MongoDB)