Search code examples
mongodbscalamongo-scala-driver

scala mongodb document getList


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.

Solution

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