0

I would like to get groups attribute as Seq[Int] from the given mongodb Document. How to do it? The method getList catches a runtime exception, and I would like to understand and fix it.

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

I tried this way that compiles, but I get the runtime error "Caused by: java.lang.ClassCastException: List element cannot be cast to scala.Int$"

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

Some sbt library dependencies:

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

Setup code:

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)
}

Comments: result is of type Seq[Document], n is of type Document.

The getList hover-on description in VSCODE:

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.
6
  • 1
    Can you give a bit more context: which libray do you use, what version? Commented Sep 6, 2021 at 17:35
  • 1
    I have updated the post. Commented Sep 6, 2021 at 17:45
  • 1
    And what is the type of n, I don't see any getList method in the API docs Commented Sep 6, 2021 at 18:00
  • 1
    I have updated the post with your comments. Commented Sep 6, 2021 at 18:08
  • 1
    val groups = n.getList("groups", classOf[Integer]) Commented Sep 6, 2021 at 19:08

1 Answer 1

1

With the help of sarveshseri and Gael J, the solution is reached:

import collection.JavaConverters._

val groups = n.getList("groups", classOf[Integer]).asScala.toSeq.map(p => p.toInt)
Sign up to request clarification or add additional context in comments.

1 Comment

Any idea on this error - value getList is not a member of org.mongodb.scala.bson.collection.mutable.Document

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.