scala mongodb 文档 getList

scala mongodb document getList

我想从给定的 mongodb 文档中获取 groups 属性作为 Seq[Int]。怎么做? getList方法捕获了一个运行时异常,我想了解并修复它。

 n: Document((_id,BsonObjectId{value=613645d689898b7d4ac2b1b2}), (groups,BsonArray{values=[BsonInt32{value=2}, BsonInt32{value=3}]}))

我试过这种编译方式,但出现运行时错误“原因:java.lang.ClassCastException:列表元素无法转换为 scala.Int$

  val groups = n.getList("groups", Int.getClass)

一些 sbt 库依赖项:

scalaVersion := "2.12.14"
libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "4.3.1"

设置代码:

val collection = db.getCollection("mylist")
Await.result(collection.drop.toFuture, Duration.Inf)
val groupsIn = Seq[Int](2, 3)
val doc = Document("groups" -> groupsIn)
Await.result(collection.insertOne(doc).toFuture, Duration.Inf)
println("see mongosh to verify that a Seq[Int] has been added")
val result = Await.result(collection.find.toFuture, Duration.Inf)
for(n <- result) {
  println("n: " + n)
  val groups = n.getList("groups", Int.getClass)
  println("groups: " + groups)
}

注释:result 是 Seq[Document] 类型,n 是 Document 类型。

VSCODE 中的 getList 悬停说明:

def getList[T](key: Any, clazz: Class[T]): java.util.List[T]
Gets the list value of the given key, casting the list elements to the given Class. This is useful to avoid having casts in client code, though the effect is the same.

sarveshseriGael J的帮助下,得到了解决方案:

import collection.JavaConverters._

val groups = n.getList("groups", classOf[Integer]).asScala.toSeq.map(p => p.toInt)