目的:在实践3中搭建了运算环境,这里学会如何使用该环境进行具体的运算和相关的排序组合等。

  • 由数据库mongodb操作如find,aggregate等可知它们的返回类型是FindObservable、AggregateObservable等,可看作每个数据库的操作都是Observable,
  • 因为之sort和projection等相应的操作都是在API中的FondObsevable里面的,且返回FondObsevable。
/**
* Sets a document describing the fields to return for all matching documents.
*
* [[http://docs.mongodb.org/manual/reference/method/db.collection.find/ Projection]]
* @param projection the project document, which may be null.
* @return this
*/
def projection(projection: Bson): FindObservable[TResult] = {
wrapped.projection(projection)
this
} /**
* Sets the sort criteria to apply to the query.
*
* [[http://docs.mongodb.org/manual/reference/method/cursor.sort/ Sort]]
* @param sort the sort criteria, which may be null.
* @return this
*/
def sort(sort: Bson): FindObservable[TResult] = {
wrapped.sort(sort)
this
}
  • 可以引入新的类型,能够便于使用
 type MGOFilterResult =  FindObservable[Document] => FindObservable[Document]

一、简单查询操作:排序、投影

 1、排序

  • 引入包

    import org.mongodb.scala.model.Sorts._
  • 在Sorts里面能看到里面的是具体方法
 /**
* Create a sort specification for an ascending sort on the given fields.
*
* @param fieldNames the field names, which must contain at least one
* @return the sort specification
* @see [[http://http://docs.mongodb.org/manual/reference/operator/meta/orderby Sort]]
*/
def ascending(fieldNames: String*): Bson = JSorts.ascending(fieldNames.asJava) /**
* Create a sort specification for an ascending sort on the given fields.
*
* @param fieldNames the field names, which must contain at least one
* @return the sort specification
* @see [[http://http://docs.mongodb.org/manual/reference/operator/meta/orderby Sort]]
*/
def descending(fieldNames: String*): Bson = JSorts.descending(fieldNames.asJava) /**
* Create a sort specification for the text score meta projection on the given field.
*
* @param fieldName the field name
* @return the sort specification
* @see [[http://http://docs.mongodb.org/manual/reference/operator/projection/meta/#sort textScore]]
*/
def metaTextScore(fieldName: String): Bson = JSorts.metaTextScore(fieldName) /**
* Combine multiple sort specifications. If any field names are repeated, the last one takes precendence.
*
* @param sorts the sort specifications
* @return the combined sort specification
*/
def orderBy(sorts: Bson*): Bson = JSorts.orderBy(sorts.asJava)
  • 应用如下:
  import org.mongodb.scala.model.Projections._
import org.mongodb.scala.model.Sorts._
val sort:MGOFilterResult=a=>a.sort(descending("age"))//“age”降序
val F1:Future[List[Document]] = DAO(dxt.setCommand(Find(andThen = Some(sort)))) F1.onComplete {
case Success(docs:List[Document]) =>
docs.foreach(Person().fromDocument(_).toSink())
println("-------------------------------")
case Failure(err) => println(s"显示错误:${err.getMessage}")
}

2、投影

  • 选择需要的字段(首页只出现商品的图片,价钱、不全部出现相关全部信息。。。)
  • 从数据库内获取字段,其他的不显示出来,这里需要对Model里面的toSink进行一些修改,使它在没有获取对应数据时,不在控制台那里显示
  def toSink()(implicit mat: ActorMaterializer) = {
println("---------------------------------------")
if (ctx.lastName!=null) {
println(s"LastName: ${ctx.lastName}")}
if (ctx.firstName!=null) {
println(s"firstName: ${ctx.firstName}")}
if (ctx.age!=) { //这里是不能设置为0的!!!其他的是空的就不理它
println(s"age: ${ctx.age}")}
if (!ctx.phones.isEmpty) {
println(s"phones: ${ctx.phones}")}
if (!ctx.address.isEmpty) {
println(s"address: ${ctx.address}")}
if (!ctx.picture.isEmpty) {
val path = s"/img/${ctx.firstName}.jpg"
FileStreaming.ByteArrayToFile(ctx.picture, path)
println(s"picture saved to: ${path}")
}
}
  • 应用如下
    import org.mongodb.scala.model.Projections._
val proj: MGOFilterResult = a => a.projection(and(include("firstName"),excludeId()))
val F2:Future[List[Document]] = DAO(dxt.setCommand(Find(andThen = Some(proj)))) F2.onComplete {
case Success(docs:List[Document]) => docs.foreach(Person().fromDocument(_).toSink())
println("-------------------------------")
case Failure(err) => println(s"显示错误:${err.getMessage}")
}

二、数据库操作的使用手册

  • 在com.mongodb.client.model包中包含CountOptions等Options,类内有各种选项。原本在casbah包内的,casbah【 end-of-life (EOL)】,迁移mongo-scala-driver。在下列的包中:

1、Count

//mongodb命令:db.personal.count({"age":{$gt:18}}) ==》结果:1
import org.mongodb.scala.model.Filters._
import com.mongodb.client.model.CountOptions._
val countOptions:CountOptions=new CountOptions().skip()
val q=dxt.setCommand(Count(Some(gt("age",)),Some(countOptions)))
DAO(q).foreach(println)//println:0

2、Distict

3、Find

//db.personal.findOne()
val p=new Person()
val ctxFindFirst :Future[Person]=DAO(dxt.setCommand(Find(converter=Some(p.fromDocument _),firstOnly=true)))
ctxFindFirst.andThen {
case Success(doc) =>doc.toSink()
//foreach(Person().fromDocument(_).toSink())
println("-------------------------------")
case Failure(err) => println(s"显示错误:${err.getMessage}")
}
===》
---------------------------------------
LastName: Wang
firstName: Susan
age:
phones: List(BsonString{value=''}, BsonString{value=''})
address: List(Address(Sz,), Address(gz,))
picture saved to: /img/Susan.jpg
-------------------------------

4、Aggregate

//db.mycol.aggregate([{$group : {_id : "$lastName", num_tutorial : {$sum : 1}}}])
import org.mongodb.scala.model.Aggregates._ val a:Bson=group("$lastName", Accumulators.sum("num_tutorial", ))
val q:Future[List[Person]]=DAO(dxt.setCommand(Aggregate(Seq(a))))
q.onComplete{
case Success(value)=>value.foreach(println)
}

注意:从org.mongodb.scala的API中可得到相关的信息,它们可以返回Bson的,但是也可以在FindObservable中看到,但是此时它们返回的类型不同。

5、MapReduce

//db.personal.mapReduce(
function() { emit(this.lastName,); },
function(key, values) {return Array.sum(values)},
{
query:{firstName:"j"},
out:"total"
}
)

6、Insert

 //db.collection.insertOne()
// db.collection.insertMany() val p1=Person("","",).toDocument
val p2=Person("","",).toDocument
val p=DAO(dxt.setCommand(Insert(Seq(p1,p2))))

7、Delete

//db.personal.remove({"age":23},1)
val p = DAO(dxt.setCommand(Delete(equal("age",),None,true)))
p.onComplete{
case Success(value)=>println("OK")
}

8、Update

 //db.personal.update({"lastName":"Wang"},{$set:{"age":18}})
org.mongodb.scala.model.Updates._
val D :Future[List[Person]]=DAO(dxt.setCommand(Update(equal("age",),set("age",""),None,true))) D.onComplete {
case Success(docs) =>println("OK")
println("-------------------------------")
case Failure(err) => println(s"显示错误:${err.getMessage}")
}

9、BulkWrite

10、DropCollection

//db.dbs.drop()
val q=DAO(dxt.setCommand(DropCollection("dbs")))
q.onComplete{
case Success(value)=>print("成功!")
}

11、CreateCollection

//db.createCollection("dbs")
val q=DAO(dxt.setCommand(CreateCollection("dbs")))
//还有options的选项,如count那里一样添加就好了
q.onComplete{
case Success(value)=>print("成功!")
}

12、ListCollection

//show tables
val q:Future[List[Document]]=DAO(dxt.setCommand(ListCollection("mydb")))
q.foreach(println)//不过出来的是比较全面信息,什么type、index都有

13、CreateView

//db.createView("View1","personal",[{$group : {_id : "$lastName", num_tutorial : {$sum : 1}}}])
import org.mongodb.scala.model.Aggregates._ val a:Bson=group("$lastName", Accumulators.sum("num_tutorial", ))
val q:Future[List[Person]]=DAO(dxt.setCommand(CreateView("View1","personal",Seq(a))))
q.onComplete{
case Success(value)=>println("OK")
}

14、CreateIndex

//db.personal.createIndex({"age":-1},{background: true})?
import org.mongodb.scala.model.Indexes._
import com.mongodb.client.model.IndexOptions._ val countOptions:IndexOptions=new IndexOptions().background(true)
val q=dxt.setCommand(CreateIndex(descending("age"),Some(IndexOptions)))//注意升降
DAO(q).onComplete{
case Success(v)=>println("成功")
}

15、DropIndexByName

//db.personal.dropIndex("date_1")
val q=dxt.setCommand(DropIndexByName("date_1"))
DAO(q).onComplete{
case Success(v)=>println("成功")
}

16、DropIndexByKey

//主要是升降ascending、descending
val q=dxt.setCommand(DropIndexByKey(ascending("age")))
DAO(q).onComplete{
case Success(v)=>println("成功")
}

17、DropAllIndexes

  val q:Future[List[Person]]=DAO(dxt.setCommand(DropAllIndexes()))
q.onComplete{
case Success(value)=>println("OK")
}
												

Scala与Mongodb实践4-----数据库操具体应用的更多相关文章

  1. Scala与Mongodb实践2-----图片、日期的存储读取

    目的:在IDEA中实现图片.日期等相关的类型在mongodb存储读取 主要是Scala和mongodb里面的类型的转换.Scala里面的数据编码类型和mongodb里面的存储的数据类型各个不同.存在类 ...

  2. Scala与Mongodb实践3-----运算环境的搭建

    目的:使的在IDEA中编辑代码,令代码实现mongodb运算,且转换较为便捷 由实验2可知,运算环境的搭建亦需要对数据进行存储和计算,故需要实现类型转换,所以在实验2的基础上搭建环境. 由菜鸟教程可得 ...

  3. Scala与Mongodb实践1-----mongodbCRUD

    目的:如何使用MongoDB之前提供有关Scala驱动程序及其异步API. 1.现有条件 IDEA中的:Scala+sbt+SDK mongodb-scala-driver的网址:http://mon ...

  4. MongoDB和Redis-NoSQL数据库-文档型-内存型

    1NoSQL简述 CAP(Consistency,Availabiity,Partitiontolerance)理论告诉我们,一个分布式系统不可能满足一致性,可用性和分区容错性这三个需求,最多只能同时 ...

  5. 使用MongoDB作为后台数据库的尝试

    MongoDB作为一个阶层型数据库,在很短的时间里面是不可能被大面积推广使用的, 本文作为一个实验性的课题,探讨一下MongoDB作为网站数据库的可能性. 1.MongoDB作为代替关系型数据库的可能 ...

  6. 使用Scala操作Mongodb

    介绍 Scala是一种功能性面向对象语言.它融汇了很多前所未有的特性.而同一时候又执行于JVM之上.随着开发人员对Scala的兴趣日增,以及越来越多的工具支持,无疑Scala语言将成为你手上一件不可缺 ...

  7. WebFlux 集成 Thymeleaf 、 Mongodb 实践 - Spring Boot(六)

    这是泥瓦匠的第105篇原创 文章工程: JDK 1.8 Maven 3.5.2 Spring Boot 2.1.3.RELEASE 工程名:springboot-webflux-5-thymeleaf ...

  8. Spring Boot WebFlu-05——WebFlux 中 Thymeleaf 和 MongoDB 实践

    第05课:WebFlux 中 Thymeleaf 和 MongoDB 实践 前言 本节内容主要还是总结上面两篇内容的操作,并实现一个复杂查询的小案例,那么没安装 MongoDB 的可以进行下面的安装流 ...

  9. MySQL、MongoDB、Redis数据库Docker镜像制作

    MySQL.MongoDB.Redis数据库Docker镜像制作 在多台主机上进行数据库部署时,如果使用传统的MySQL的交互式的安装方式将会重复很多遍.如果做成镜像,那么我们只需要make once ...

随机推荐

  1. H3C 帧中继基本配置命令

  2. Mockito 使用

    1. 算术测试类 package com.smart.test.mockito; public interface Calculator { public int add(int a, int b); ...

  3. H3C 最大跳数16导致网络尺度小

  4. 2018-2-13-wpf-使用-Dispatcher.Invoke-冻结窗口

    title author date CreateTime categories wpf 使用 Dispatcher.Invoke 冻结窗口 lindexi 2018-2-13 17:23:3 +080 ...

  5. P1075 语句解析

    题目描述 一串长度不超过 255 的 PASCAL 语言代码,只有 a,b,c 3 个变量,而且只有赋值语句,赋值只能是一个一位的数字或一个变量,每条赋值语句的格式是 [变量]:=[变量或一位整数]; ...

  6. dotnet 特性 DynamicallyInvokable 是用来做什么的

    我在 Linq 很多函数都看到 __DynamicallyInvokable 这个特性,这是一个没有官方文档的特性,也许是用来优化反射 在堆栈 网找到了以下描述 这个 __DynamicallyInv ...

  7. gulp插件使用

    //引入gulp组件 var gulp=require('gulp'); //创建任务 gulp.task('hello',function(){ console.log('hello'); }); ...

  8. CITRIX VPX配置四层负载

    网络拓扑如下: Step1:开启四层负载特性 在Configuration->Traffic Management->Load Balancing上右键弹出菜单点击enable,如下图: ...

  9. jsp中点击一个图片跳转到另一个页面的方法

    1.这是jsp页面中的关于图片的那段代码 <img src="images/tj1.png " id="tj1"></img> 2.跳转 ...

  10. Go处理PDF

    工作中经常会遇到一些pdf文件处理的问题,一千种pdf有一千种处理方式,每次都是绞尽脑汁和这些pdf战斗到底. 本人又是一个gopher,所以这篇文章会以一个goper的视角,列举一下我所经历过的每一 ...