Scala對MongoDB的增刪改查操做 Scala對MongoDB的增刪改查操做 MongoDB學習筆記(查詢)

===========================================html

    原文連接: Scala對MongoDB的增刪改查操做 轉載請註明出處!java

===========================================mongodb

依賴環境:jdk1.八、Scala 2.十二、idea數據庫

    mongodb Driver:3.1.1。注意,mongo for scala的驅動涉及多個jar(以下圖),依賴於mongo-java-driver.jarapp

    這裏使用的sbt管理依賴,直接在build.sbt中添加依賴:libraryDependencies += "org.mongodb" %% "casbah" % "3.1.1"(強烈建議使用該方法添加依賴)ide

1、建立數據庫鏈接函數

A:不須要用戶名和密碼直接獲取MongoDB。post

  //  無權限驗證鏈接
  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
*/

 2、數據添加

  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"}}

3、數據更新修改

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」模式進行定義】。源碼以下:

 

4、數據查詢(建議看下這篇文章: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))
  }

 

 查詢結果以下:

5、數據刪除

數據刪除主要是構建一個查詢條件,把符合該條件的全部數據都進行刪除

  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

相關文章
相關標籤/搜索