Mongo Scala驱动程序集合不会更新文档

时间:2016-06-09 16:15:25

标签: mongodb scala mongo-scala-driver

我能够插入,读取和删除但是我无法获得updateOne或updateMany来修改文档。

我正在使用MongoDB 3.2.7 with libraryDependencies + =“org.mongodb.scala”%%“mongo-scala-driver”%“1.1.1”

def read() = {
val query = Document("title" -> "Text Tiling")
methods.find(query).subscribe(
  (method: Document) => update(method.toJson()),                              // onNext
  (error: Throwable) => Logger.debug(s"Query failed: ${error.getMessage}"),   // onError
  () => Logger.debug("onComplete")                                            // onComplete
)}

def update(jsonSting:String): Unit = {
Logger.debug("update() " + jsonSting)

Logger.debug(methods.find().first().toString)
val observer = new Observer[UpdateResult] {
  override def onSubscribe(subscription: Subscription): Unit = {
    Logger.debug("onSubscribe: " + subscription.toString)
  }
  override def onComplete: Unit = {
    Logger.debug("onComplete")
  }
  override def onError(e: Throwable): Unit = {
    Logger.debug("onError: " + e.getMessage)
  }
  override def onNext(doc: UpdateResult) {
    Logger.debug("onNext")
  }
}

val filter = Document("title" -> "Text Tiling")
val mod = Document("$set" -> Document("reputation" -> 5))
val result = methods.updateOne(filter,mod).subscribe(observer)
Logger.debug("result: " + result)}

以下是日志:

[debug] application - update(){“_ id”:{“$ oid”:“5759542a4e0bf602adcab149”},“title”:“Text Tiling”,“reputation”:0}

[debug] application - org.mongodb.scala.ObservableImplicits$BoxedObservable@61ddc581

[debug] application - onSubscribe:org.mongodb.scala.ObservableImplicits$BoxedSubscription@6252b659

[debug] application - result :()

[debug] application - onComplete

2 个答案:

答案 0 :(得分:2)

订阅上的呼叫请求对我有用。其他事件随后被召唤。

override def onSubscribe(subscription: Subscription): Unit = {
    subscription.request(1)
  }

[debug] application - onNext

[debug] application - onComplete!

答案 1 :(得分:0)

val filter : Bson = new Document(“key”, “old_value”) 
val newValue : Bson = new Document(“key” ,”new_value”)
val updateOperationDocument : Bson = new Document("$set", newValue)
val collection = db.getCollection(“collection_name”)
collection.updateOne(filter, updateOperationDocument)