2015-10-23 55 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