MongoDB with Scala language

673 Views Asked by At

i am new to MongoDB and Scala language

i am using scala language to connect mongodb locally

i am using below dependency

// https://mvnrepository.com/artifact/org.mongodb.scala/mongo-scala-driver

libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "4.2.3"

what I tried

object Demo extends App {
  
  val mongoClient: MongoClient = MongoClient("mongodb://127.0.0.1:27017/")
  val database: MongoDatabase = mongoClient.getDatabase("DemoDB")
  println(database)

  val collection: MongoCollection[Document] =database.getCollection("demodata");
  val observable = collection.find();
}

the above code returning the data in below format

FindObservable(com.mongodb.reactivestreams.client.internal.FindPublisherImpl@6253c26)

I also tried with

observable.subscribe ( new Observer[Document] {
  override def onNext(result: Document): Unit = println(result.toJson())
  override def onError(e: Throwable): Unit = println("Failed" + e.getMessage)
  override def onComplete(): Unit = println("Completed")
})

i also tried printResult() and printHeadResult() method also but none of the way is working

please help thanks in advance

2

There are 2 best solutions below

1
On BEST ANSWER

Mongo Scala driver works in a non-blocking manner by returning Observables which need to be Subsribed on to consume the published data.

When you are subscribing to the observable like following,

object Demo extends App {
  
  val mongoClient: MongoClient = MongoClient("mongodb://127.0.0.1:27017/")
  val database: MongoDatabase = mongoClient.getDatabase("DemoDB")
  println(database)

  val collection: MongoCollection[Document] = database.getCollection("demodata")
  val observable = collection.find()

  observable.subscribe ( new Observer[Document] {
    override def onNext(result: Document): Unit = println(result.toJson())
    override def onError(e: Throwable): Unit = println("Failed" + e.getMessage)
    override def onComplete(): Unit = println("Completed")
  })
}

Your code does not wait for observable to actually publish anything, it just finishes right after subscribing. Hence you don't get anything.

You can either add a Something like a Thread.sleep(5000) at the end to block and give the obeservable some time to (hopefully finish and) publish the data.

Or, you can add val resultSeq = observable.collect to block and collect all of published data in a single Sequence.

0
On

I found this link

it works for printResult() and printHeadResult() method

Printing query results from Mongodb in Scala using mongo-scala-driver