[英]Unable to make connection to MongoDB using MongoDB Scala Driver
I am using Scala driver for MongoDB to make a connection and insert a document in the class.我正在使用 MongoDB 的 Scala 驱动程序建立连接并在类中插入文档。 I am following their official documentation as mentioned in this link.
我正在关注此链接中提到的他们的官方文档。 ( http://mongodb.github.io/mongo-scala-driver/2.6/getting-started/quick-tour/ )
( 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.我在 Windows 10 上运行 MongoDB,并且作为独立的而不是在集群设置中运行。 When I run the scala code, I see following log entry and error and nothing happens.
当我运行 scala 代码时,我看到以下日志条目和错误,但没有任何反应。
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?有人指出我做错了什么吗?
I had the same problem and fixed it by adding Thread.sleep(1000)
at the end of my program.我遇到了同样的问题,并通过在我的程序末尾添加
Thread.sleep(1000)
来修复它。 Apparently it closes the connection before it finishes the operation and so nothing happens.显然它在完成操作之前关闭了连接,所以什么也没有发生。 I'm sure there is a more elegant solution though.
不过,我确信有一个更优雅的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.