我想从给定的 mongodb 文档中获取组属性作为 Seq[Int] 。怎么做?getList方法捕获运行时异常,我想了解并修复它。
n: Document((_id,BsonObjectId{value=613645d689898b7d4ac2b1b2}), (groups,BsonArray{values=[BsonInt32{value=2}, BsonInt32{value=3}]}))
我尝试了这种编译方式,但出现运行时错误“ Caused by: java.lang.ClassCastException: List element cannot be cast to 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)
}
注释:结果是 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.