Scala与Mongodb实践4-----数据库操具体应用
目的:在实践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-----数据库操具体应用的更多相关文章
- Scala与Mongodb实践2-----图片、日期的存储读取
目的:在IDEA中实现图片.日期等相关的类型在mongodb存储读取 主要是Scala和mongodb里面的类型的转换.Scala里面的数据编码类型和mongodb里面的存储的数据类型各个不同.存在类 ...
- Scala与Mongodb实践3-----运算环境的搭建
目的:使的在IDEA中编辑代码,令代码实现mongodb运算,且转换较为便捷 由实验2可知,运算环境的搭建亦需要对数据进行存储和计算,故需要实现类型转换,所以在实验2的基础上搭建环境. 由菜鸟教程可得 ...
- Scala与Mongodb实践1-----mongodbCRUD
目的:如何使用MongoDB之前提供有关Scala驱动程序及其异步API. 1.现有条件 IDEA中的:Scala+sbt+SDK mongodb-scala-driver的网址:http://mon ...
- MongoDB和Redis-NoSQL数据库-文档型-内存型
1NoSQL简述 CAP(Consistency,Availabiity,Partitiontolerance)理论告诉我们,一个分布式系统不可能满足一致性,可用性和分区容错性这三个需求,最多只能同时 ...
- 使用MongoDB作为后台数据库的尝试
MongoDB作为一个阶层型数据库,在很短的时间里面是不可能被大面积推广使用的, 本文作为一个实验性的课题,探讨一下MongoDB作为网站数据库的可能性. 1.MongoDB作为代替关系型数据库的可能 ...
- 使用Scala操作Mongodb
介绍 Scala是一种功能性面向对象语言.它融汇了很多前所未有的特性.而同一时候又执行于JVM之上.随着开发人员对Scala的兴趣日增,以及越来越多的工具支持,无疑Scala语言将成为你手上一件不可缺 ...
- WebFlux 集成 Thymeleaf 、 Mongodb 实践 - Spring Boot(六)
这是泥瓦匠的第105篇原创 文章工程: JDK 1.8 Maven 3.5.2 Spring Boot 2.1.3.RELEASE 工程名:springboot-webflux-5-thymeleaf ...
- Spring Boot WebFlu-05——WebFlux 中 Thymeleaf 和 MongoDB 实践
第05课:WebFlux 中 Thymeleaf 和 MongoDB 实践 前言 本节内容主要还是总结上面两篇内容的操作,并实现一个复杂查询的小案例,那么没安装 MongoDB 的可以进行下面的安装流 ...
- MySQL、MongoDB、Redis数据库Docker镜像制作
MySQL.MongoDB.Redis数据库Docker镜像制作 在多台主机上进行数据库部署时,如果使用传统的MySQL的交互式的安装方式将会重复很多遍.如果做成镜像,那么我们只需要make once ...
随机推荐
- Python--day62--删除出版社
删除成出版社关键代码:
- js 制作分页
如图所示 在html中调用方法 getpage(7, 1, 1, 'URL') 1.page.js文件 代码 function getpage(count, countPage, pageIndex, ...
- 在spring security3中使用自定义的MD5和salt进行加密
首先看代码: <authentication-manager alias="authenticationManager"> <authentication-pro ...
- 总结:关于留学网站使用laravel框架的总结
1.从git库中clone后本地项目根目录没有vendor文件夹,安装composer 2.composer install 报错 ,删除 composer.lock 文件,重新执行 composer ...
- 12627 - Erratic Expansion——[递归]
Piotr found a magical box in heaven. Its magic power is that if you place any red balloon inside it ...
- tensorflow在文本处理中的使用——CBOW词嵌入模型
代码来源于:tensorflow机器学习实战指南(曾益强 译,2017年9月)——第七章:自然语言处理 代码地址:https://github.com/nfmcclure/tensorflow-coo ...
- 修改github上的项目语言类型
当在github上上传一个项目时,可能会出现一个问题就是项目代码类型是自动生成的,可能与我们实际项目代码种类不匹配,此时就需要修改项目语言类型了. 由于无法直接更改,所以用到此方法: 在你的项目根目录 ...
- vue-learning:31 - component - 组件间通信的6种方法
vue组件间通信的6种方法 父子组件通信 prop / $emit 嵌套组件 $attrs / $liteners 后代组件通信 provide / inject 组件实例引用 $root / $pa ...
- SDOI2019热闹又尴尬的聚会
P5361 [SDOI2019]热闹又尴尬的聚会 出题人用脚造数据系列 只要将\(p\)最大的只求出来,\(q\)直接随便rand就能过 真的是 我们说说怎么求最大的\(p\),这个玩意具有很明显的单 ...
- ios设备iframe无法滚动
在使用IFRAME,你需要使用一个元素(如DIV)来包装他们 <div class="scroll-wrapper"> <iframe src="&qu ...