===========================================
===========================================
依赖环境:jdk1.8、Scala 2.12、idea
mongodb Driver:3.1.1。注意,mongo for scala的驱动涉及多个jar(如下图),依赖于mongo-java-driver.jar
这里使用的sbt管理依赖,直接在build.sbt中添加依赖:libraryDependencies += "org.mongodb" %% "casbah" % "3.1.1"(强烈建议使用该方法添加依赖)
一、创建数据库连接
A:不需要用户名和密码直接获取MongoDB。
//无权限验证连接
def createDatabase(url: String, port: Int, dbName: String): MongoDB ={
MongoClient(url, port).getDB(dbName)
}
这里需要注意一下,在导入的jar包存在两个MongoClient类,一个来自于mongo-java-driver.jar的com.mongodb.MongoClient,另一个来自于casbah-core_2.12:3.1.1.jar的com.mongodb.casbah.MongoClient.前者是用于java调用,Scala使用后者!!!
因此导入包的时候要注意为:import com.mongodb.casbah.MongoClient
B:通过权限验证进行连接
//验证连接权限
def createDatabase(url: String, port: Int, dbName: String, loginName: String, password: String): MongoDB ={
var server= newServerAddress(url, port)//注意:MongoCredential中有6种创建连接方式,这里使用MONGODB_CR机制进行连接。如果选择错误则会发生权限验证失败
var credentials =MongoCredential.createCredential(loginName, dbName, password.toCharArray)
var mongoClient=MongoClient(server, List(credentials))
mongoClient.getDB(dbName)
}
这里需要注意的是MongoCredential.createCredential(),在MongoCredential中存在着六种认证机制,这里使用createCredential()进行创建,使用错误则将会验证失败
com.mongodb.MongoSecurityException: Exception authenticating
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'auth failed' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18, "codeName" : "AuthenticationFailed" }
该方法注释如下:
/**
* Creates a MongoCredential instance with an unspecified mechanism. The client will negotiate the best mechanism
* based on the version of the server that the client is authenticating to. If the server version is 2.8 or higher,
* the driver will authenticate using the SCRAM-SHA-1 mechanism. Otherwise, the driver will authenticate using the
* MONGODB_CR mechanism.
*
* @param userName the user name
* @param database the database where the user is defined
* @param password the user's password
*/
二、数据添加
def testInsert(): Unit ={for (i
collection.insert(MongoDBObject("name" -> "Jack%d".format(i), "email" -> "jack%d@sina.com".format(i), "age" -> i % 25, "birthDay" -> new SimpleDateFormat("yyyy-MM-dd").parse("2016-03-25")))
}
这里的collection是在下面创建的:
var collection= createDatabase("localhost", 27017, "mytest", "user", "123456").getCollection("user")
在进行数据插