0

I am using Scala driver for MongoDB to make a connection and insert a document in the class. I am following their official documentation as mentioned in this link. (http://mongodb.github.io/mongo-scala-driver/2.6/getting-started/quick-tour/)

I am running MongoDB on the windows 10 and as standalone not in the cluster setup. When I run the scala code, I see following log entry and error and nothing happens.

Log Info:

373 [main] INFO org.mongodb.driver.cluster - Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}

510 [main] INFO org.mongodb.driver.cluster - No server chosen by com.mongodb.async.client.ClientSessionHelper$1@702657cc from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out

Sbt File:

ame := "TestModule"

version := "0.1"

scalaVersion := "2.12.8"

libraryDependencies += "org.apache.kafka" %% "kafka" % "2.1.0"
libraryDependencies += "org.slf4j" % "slf4j-simple" % "1.7.0"
libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "2.6.0"

Scala Code:

import org.mongodb.scala._

object MongoDBManager {

  def main(args: Array[String]): Unit ={


    // Making connection with a database made in the MongoDB
    // Use a Connection String
    val mongoClient: MongoClient = MongoClient("mongodb://localhost")

    // Connect with the Database
    val database: MongoDatabase = mongoClient.getDatabase("poc")

    //Get the Collection
    val collection: MongoCollection[Document] = database.getCollection("poc_json")

    //make a sample json document
    val doc: Document = Document("_id" -> 2, "name" -> "MongoDB", "type" -> "database", "count" -> 1)

    // Insert the Document into the MongoDB.

    val observable: Observable[Completed] = collection.insertOne(doc)
    //Explicitly subscribe:
    observable.subscribe(new Observer[Completed] {

      override def onNext(result: Completed): Unit = println("Inserted")

      override def onError(e: Throwable): Unit = println("Failed")

      override def onComplete(): Unit = println("Completed")
    })



  }
}

Do anybody point out that what am I doing wrong?

omer khalid
  • 855
  • 1
  • 12
  • 39

1 Answers1

0

I had the same problem and fixed it by adding Thread.sleep(1000) at the end of my program. Apparently it closes the connection before it finishes the operation and so nothing happens. I'm sure there is a more elegant solution though.

VeryNice
  • 71
  • 6