2015-10-23 60 views
1

我在我的MongoDB數據庫中有一個集合,裏面有幾個鍵。現在我想用一個新字段更新這個集合。所以這是我到目前爲止有:ReactiveMongo FindAndModify澄清

def confirm(hash: String) = { 

    val myDb = dbConn.db(dbName) 
    val userCollection = myDb[BSONCollection]("user") 

    val selector = BSONDocument(idKey -> BSONObjectID(hash)) 
    val modifier = BSONDocument(
     "$set" -> BSONDocument("date" -> BSONString(now.toString)) // Line 1 
    ) 

    val command = FindAndModify(
     userCollection.name, 
     selector, 
     Update(modifier, fetchNewObject = true) 
    ) 

    myDb.command(command) 
     .map { user => // Line 2 
     Right(bidList) 
    }.recover { 
     case LastError(ok,err, code, errMsg, _) => 
     Left(ServiceError(errMsg.getOrElse("failure!"))) 
    } 
    } 

我有兩個問題上面的實現:

1號線:這會更新一個名爲date新領域存在的文件呢?

在線2:映射myDb.command(命令)給了我一個選項[BSONDocument],但我很驚訝的是我有一個隱式轉換範圍。所以我會期待它返回一個選項[用戶]!

+0

您不指明您使用的是哪個版本。在RM 0.11.7中,您有收集操作'.findAndUpdate'。 – cchantep

+0

這是針對MongoDB的ReactiveMongo 0.11.7 3.0.6 – sparkr

+0

你可以看看[.findAndUpdate](http://reactivemongo.org/releases/0.11/api/index.html#reactivemongo.api.collections.GenericCollection findAndUpdate [Q,U]%28selector:Q,更新:U,fetchNewObject:布爾,UPSERT:布爾,排序:選項[GenericCollection.this.pack.Document],字段:選項[GenericCollection.this.pack.Document]%29 %28implicitselectorWriter:GenericCollection.this.pack.Writer [Q],implicitupdateWriter:GenericCollection.this.pack.Writer [U],implicitec:scala.concurrent.ExecutionContext%29:scala.concurrent.Future [GenericCollection.this.BatchCommands.FindAndModifyCommand .FindAndModifyResult]) – cchantep

回答

3

你可以看看.findAndUpdateFindAndModifyResult,它提供了一個.result操作來根據可用的BSON閱讀器獲取結果。

val person: Future[Option[AType]] = collection.findAndUpdate(
    BSONDocument("name" -> "James"), 
    BSONDocument("$set" -> BSONDocument("age" -> 17)), 
    fetchNewObject = true).map(_.result[AType]) 
+0

你正在使用哪個API版本?如果我嘗試你的例子,我沒有收到Future [BSONDocument]回來?我在ReactiveMongo API上使用0.11.7版本 – sparkr

1

我剛剛花了一些時間尋找play-reactivemongo等價物。也許這個例子將來有助於某人。

val collectionFut: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("sale.numberingCounter")) 

def updateIdx(nsId: NumberingSeriesId, month: Option[Int], year: Option[Int], value: Int): Future[Option[NumberingCounter]] = { 
val selector = Json.obj("numberingSeriesId" -> nsId, "month" -> month, "year" -> year)   
val modifier = Json.obj("$set" -> Json.obj("idx" -> value)) 
    for { 
     collection <- collectionFut 
     writeResult <- collection.findAndUpdate(selector,modifier,upsert = true) 
    } yield { 
     writeResult.value.map(_.as[NumberingCounter]) 
    } 
    } 
+0

感謝您的努力! – sparkr