===========================================
原文鏈接: Scala對MongoDB的增刪改查操作 轉載請注明出處!
===========================================
依賴環境: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 = new ServerAddress(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 <- 1 to 100) 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")
在進行數據插入的時候,如果不存在該collection則會自動創建(這里是user),如果document中不包含“_id”字段則會自動添加該字段。
DBCollection中存在一個save方法,該save方法區別於insert的地方在於當“_id”存在於集合中,save將會進行更新數據,而insert不會進行任何操作
根據需要選擇適合的數據插入函數
存儲之后數據如下:
{ "_id" : { "$oid" : "592ad4be45aefd09f4867f1e"} , "name" : "Jack86" , "email" : "jack86@sina.com" , "age" : 11 , "birthDay" : { "$date" : "2016-03-24T16:00:00.000Z"}}
{ "_id" : { "$oid" : "592ad4be45aefd09f4867f1f"} , "name" : "Jack87" , "email" : "jack87@sina.com" , "age" : 12 , "birthDay" : { "$date" : "2016-03-24T16:00:00.000Z"}}
{ "_id" : { "$oid" : "592ad4be45aefd09f4867f20"} , "name" : "Jack88" , "email" : "jack88@sina.com" , "age" : 13 , "birthDay" : { "$date" : "2016-03-24T16:00:00.000Z"}}
{ "_id" : { "$oid" : "592ad4be45aefd09f4867f21"} , "name" : "Jack89" , "email" : "jack89@sina.com" , "age" : 14 , "birthDay" : { "$date" : "2016-03-24T16:00:00.000Z"}}
三、數據更新修改
A:更新方式一
def testUpdate(): Unit = { var query = MongoDBObject("name" -> "user1", "email" -> "user1@test.com") var value = MongoDBObject("name" -> "user1", "email" -> "user1@test.com123456") println("=========更新之前============") var query02 = MongoDBObject("name" -> "user1") collection.find(query02).forEach(x => println(x)) // query:根據此條件進行查詢 value:把查詢出來結果集的第一條數據設置為value collection.update(query,value) println("=========更新之后============") collection.find(query02).forEach(x => println(x)) }
運行結果如下:(注意這里只更新了一條記錄,並不是把所有符合結果的數據都進行更新)
B:更新方式二
def testUpdate02(): Unit = { var query = MongoDBObject("name" -> "user1", "email" -> "user1@test.com123456") var value = new BasicDBObject("$set", new BasicDBObject("email", "user1@test.com")) // var value = MongoDBObject("$set",MongoDBObject("name" -> "user1", "email" -> "user1@test.com123")) println("=========更新之前============") var query02 = MongoDBObject("name" -> "user1") collection.find(query02).forEach(x => println(x)) collection.update(query, value,true, true) println("=========更新之后============") collection.find(query02).forEach(x => println(x)) }
注意該方法:collection.update(query, value,true, true)。
第三個參數:when true, inserts a document if no document matches the update query criteria
第四個參數:when true, updates all documents in the collection that match the update query criteria, otherwise only updates one【當該值為true時,則更新所有的結果集數據,不過前提是value必須使用“$XXX”模式進行定義】。源碼如下:
四、數據查詢(建議看下這篇文章:MongoDB學習筆記(查詢))
def testSelect(): Unit ={ println("=========查詢所有數據===================") collection.find().forEach(x => println(x)) println("=========查詢name = “user1” 同時email=“user1@test.com”===================") collection.find(MongoDBObject("name" -> "user1", "email" -> "user1@test.com")).limit(3).forEach(x => println(x)) // 注意此處不能使用put添加其他查詢條件,因為put返回的是HashMap,此處應該使用append進行添加查詢條件 // var query = new BasicDBObject("name",new BasicDBObject("$in",("user145","user155"))).put("qty",new BasicDBObject("$in",(25.0,105.0))) 該方法錯誤 // 查詢條件為: (name in ("user145","user155")) && (qty in (25.0,105.0)) println("=========查詢 (name in (\"user145\",\"user155\")) && (qty in (25.0,105.0))===================") var query = new BasicDBObject("name", new BasicDBObject("$in", ("user145", "user155"))).append("qty", new BasicDBObject("$in", (25.0, 105.0))) collection.find(query).forEach(x => println(x)) println("=========查詢 start >= 10 && end<= 80 的數據===================") var query02 = new BasicDBObject("start", new BasicDBObject("$gte", 10)).append("end", new BasicDBObject("$lte", 80)) collection.find(query02).forEach(x => println(x)) }
查詢結果如下:
五、數據刪除
數據刪除主要是構建一個查詢條件,把符合該條件的所有數據都進行刪除
def testDelete(): Unit ={ var query = MongoDBObject("name" -> "user1", "email" -> "user1@test.com") println("=========刪除之前============") collection.find(query).forEach(x => println(x)) //該參數只是一個查詢條件,符合該條件的所有集合都將被刪除。重點在於如何構建query collection.remove(query) println("=========刪除之前============") collection.find(query).forEach(x => println(x)) }
執行結果如下:
=========刪除之前============
{ "_id" : { "$oid" : "592a0c8345aefd1d404c3ed9"} , "name" : "user1" , "email" : "user1@test.com"}
{ "_id" : { "$oid" : "592a0c8345aefd1d404c3eda"} , "name" : "user1" , "email" : "user1@test.com"}
{ "_id" : { "$oid" : "592a0c9845aefd0dfc2a1e21"} , "name" : "user1" , "email" : "user1@test.com"}
{ "_id" : { "$oid" : "592a0c9845aefd0dfc2a1e23"} , "name" : "user1" , "email" : "user1@test.com"}
{ "_id" : { "$oid" : "592a740f434a43d3b1529d0e"} , "name" : "user1" , "email" : "user1@test.com"}
=========刪除之后============
remove方法有如下四種,根據具體情況選取合適的方法:

附測試源碼:
package tool import java.text.SimpleDateFormat import java.util import java.util.Date import com.mongodb.casbah.commons.MongoDBObject import com.mongodb.{BasicDBObject, DBCollection, ServerAddress} import com.mongodb.casbah.{MongoClient, MongoCredential, MongoDB} import com.mongodb.client.model.Filters import org.joda.time.DateTime /** * Created with IntelliJ IDEA. * Description: * User: Perkins Zhu * Date: 2017-05-28 * Time: 19:33 */ object MongoTool { def main(args: Array[String]): Unit = { // testInsert // testUpdate02 // testSelect testDelete } def testDelete(): Unit ={ var query = MongoDBObject("name" -> "user1", "email" -> "user1@test.com") println("=========刪除之前============") collection.find(query).forEach(x => println(x)) //該參數只是一個查詢條件,符合該條件的所有集合都將被刪除 collection.remove(query) collection.findAndRemove() println("=========刪除之前============") collection.find(query).forEach(x => println(x)) } def testUpdate01(): Unit = { var query = MongoDBObject("name" -> "user1", "email" -> "user1@test.com") var value = MongoDBObject("name" -> "user1", "email" -> "user1@test.com123456") println("=========更新之前============") var query02 = MongoDBObject("name" -> "user1") collection.find(query02).forEach(x => println(x)) // query:根據此條件進行查詢 value:把查詢出來結果集的第一條數據設置為value collection.update(query,value) println("=========更新之后============") collection.find(query02).forEach(x => println(x)) } def testUpdate02(): Unit = { var query = MongoDBObject("name" -> "user1", "email" -> "user1@test.com123456") var value = new BasicDBObject("$set", new BasicDBObject("email", "user1@test.com")) // var value = MongoDBObject("$set",MongoDBObject("name" -> "user1", "email" -> "user1@test.com123")) println("=========更新之前============") var query02 = MongoDBObject("name" -> "user1") collection.find(query02).forEach(x => println(x)) collection.update(query, value,true, true) println("=========更新之后============") collection.find(query02).forEach(x => println(x)) } def testSelect(): Unit ={ println("=========查詢所有數據===================") collection.find().forEach(x => println(x)) println("=========查詢name = “user1” 同時email=“user1@test.com”===================") collection.find(MongoDBObject("name" -> "user1", "email" -> "user1@test.com")).limit(3).forEach(x => println(x)) // 注意此處不能使用put添加其他查詢條件,因為put返回的是HashMap,此處應該使用append進行添加查詢條件 // var query = new BasicDBObject("name",new BasicDBObject("$in",("user145","user155"))).put("qty",new BasicDBObject("$in",(25.0,105.0))) 該方法錯誤 // 查詢條件為: (name in ("user145","user155")) && (qty in (25.0,105.0)) println("=========查詢 (name in (\"user145\",\"user155\")) && (qty in (25.0,105.0))===================") var query = new BasicDBObject("name", new BasicDBObject("$in", ("user145", "user155"))).append("qty", new BasicDBObject("$in", (25.0, 105.0))) collection.find(query).forEach(x => println(x)) println("=========查詢 start >= 10 && end<= 80 的數據===================") var query02 = new BasicDBObject("start", new BasicDBObject("$gte", 10)).append("end", new BasicDBObject("$lte", 80)) collection.find(query02).forEach(x => println(x)) } def testInsert(): Unit = { for (i <- 1 to 100) // 注意與saved的區別 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"))) } var collection = createDatabase("localhost", 27017, "mytest", "user", "123456").getCollection("user") //驗證連接權限 def createDatabase(url: String, port: Int, dbName: String, loginName: String, password: String): MongoDB = { var server = new ServerAddress(url, port) //注意:MongoCredential中有6種創建連接方式,這里使用MONGODB_CR機制進行連接。如果選擇錯誤則會發生權限驗證失敗 var credentials = MongoCredential.createCredential(loginName, dbName, password.toCharArray) var mongoClient = MongoClient(server, List(credentials)) mongoClient.getDB(dbName) } // 無權限驗證連接 def createDatabase(url: String, port: Int, dbName: String): MongoDB = { MongoClient(url, port).getDB(dbName) } }
--end