无法使用MongoDB Scala驱动程序建立与MongoDB的连接

时间:2019-04-19 21:51:28

标签: mongodb scala mongodb-query mongodb-scala

我正在使用用于MongoDB的Scala驱动程序进行连接并在类中插入文档。我正在关注此链接中提到的他们的官方文档。 (http://mongodb.github.io/mongo-scala-driver/2.6/getting-started/quick-tour/

我在Windows 10上以独立方式运行MongoDB,而不是在群集设置中。当我运行scala代码时,我看到以下日志条目和错误,但没有任何反应。

日志信息:

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文件:

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"

标量代码:

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



  }
}

有人指出我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并通过在程序末尾添加Thread.sleep(1000)来解决了该问题。显然,它在完成操作之前就关闭了连接,因此什么也没发生。我敢肯定还有更好的解决方案。