从Scala的Mongo DB将文档字段收集到数组

时间:2019-02-25 04:03:10

标签: mongodb scala bson subscribe

因此,我有按以下方式查询的来自Mongo DB的页面浏览量评分的新闻文章集合:

// To directly connect to the default server localhost on port 27017
val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
val database: MongoDatabase = mongoClient.getDatabase("Posts")
var collection: MongoCollection[Document] = database.getCollection("news")

collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>println(s"${doc.get("views")}"))

此打印:

Some(BsonInt32{value=66043})
Some(BsonInt32{value=66306})
Some(BsonInt32{value=66336})
Some(BsonInt32{value=66365})
Some(BsonInt32{value=66384})

所以现在我想将所有这些值收集到一个数组中,这是我尝试通过以下代码行完成的:

var scores = collection.find(equal("id","id123")).limit(5).subscribe((doc: Document)=>doc.get("score").map(_.asInt32().getValue).collect())

但是.collect()不起作用。

将Mongo字段转换为整数数组的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我想出了一个解决方案,尽管我不完全理解它:

import org.mongodb.scala._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.model.Projections._

object main extends App {
  //Connect to Mongo Client and DB
  val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
  val database: MongoDatabase = mongoClient.getDatabase("MyDatabase")

  //Get Collection
  val collection: MongoCollection[Document] = database.getCollection("collectionName")

  //Returns the object with specified fields in projection 
  //as a Future observable containing MongoDB Documents
  val collScores = collection.find(equal("id","id123")).limit(5).projection(fields(include("id", "score", "time"), excludeId()))

  //Maps the document fields to tuples and converts them 
  //to non BSon values since they are easier to work with 
  //than future observables.
  val listMapScores = collScores.map(doc=>(doc("id").asString.getValue,doc("score").asInt32.getValue,doc("time").asDouble.getValue)).collect().results().head 

}

我不确定为什么您需要在最后一行中同时做results()head。如果您不使用head,则最终会得到Seq[Seq(String,Int)]]。据我所知,无论您采用该系列中的head还是Nth术语,未来的observable都包含相同的值。