目的:如何使用MongoDB之前提供有关Scala驱动程序及其异步API。
1、现有条件
- IDEA中的:Scala+sbt+SDK
- mongodb-scala-driver的网址:http://mongodb.github.io/mongo-scala-driver/2.6/getting-started/installation-guide/
注:Scala13太新,driver2.6.0是在Scala2.12中的
2、添加依赖包
libraryDependencies := Seq( "org.mongodb.scala" %% "mongo-scala-driver" % "2.6.0", "com.lightbend.akka" %% "akka-stream-alpakka-mongodb" % "0.20" )
3、连接mongodb
//方法1:简单连接 val client1=MongoClient("mongodb://192.168.1.135:27017") //方法2:可添加条件的连接(.build()前面) val settings: MongoClientSettings = MongoClientSettings.builder() .applyToClusterSettings(b => b.hosts(List(new ServerAddress("192.168.1.135")).asJava)) .build() val mongoClient: MongoClient = MongoClient(settings)
4、选择database、collection
val database: MongoDatabase = mongoClient.getDatabase("testdb") val collection:MongoCollection[Document]=database.getCollection("test")
然后Document可以通过CanbeBsonElement构建。CanbeBsonElement是一种key/value结构
val Lily=Document("id"->1,"name"->"Lily","age"->22) val Luzy=Document("city"->"shenzhen","capital"->"beijin","age"->"Luzy")
5、数据操作
- 订阅
//在API中,Observables都是“冷”流,在订阅之前不会发生任何事情。可以把数据库中各种操作如find、insertOne等都是一个Observable val addLily: Observable[Completed] =collection.insertOne(Lily) val addLuzy=collection.insertOne(Luzy) //1、addLily //Scala API使用Observer模式的自定义实现异步编程 //Observable订阅并且请求的数据才会发生操作 addLily.subscribe(new Observer[Completed]{ override def onComplete():Unit=println("insert lily complete.") override def onNext(result: Completed):Unit=println("insert lily sucessful!") override def onError(e:Throwable):Unit=println(s"insert error:${e.getMessage}") })
- Helper(内含headResult等方法)的headResult
//2、addLuzy def headResult(observable: Observable[Completed])=Await.result(observable.head(),2 seconds) val r1=headResult(addLuzy)
- onComplete
// 删除文件 val deleteAll=collection.deleteMany(notEqual("id",1)) deleteAll.head.onComplete{ case Success(v)=>println(s"delete successful $v") case Failure(e)=>println(s"delete error:${e.getMessage}") } //异步读取 scala.io.StdIn.readLine()
6、还有增删改查之类各种文档、索引等操作
http://mongodb.github.io/mongo-scala-driver/2.6/getting-started/quick-tour/
7、关闭连接
mongoClient.close()