问题
I have a collection in my MongoDB database with say several keys. Now I want to update this collection with a new field. So here is what I have so far:
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!")))
}
}
I have two problems with the above implementation:
On Line 1: Would this update the existing document with a new field called date?
On Line 2: Mapping the myDb.command(command) gives me an Option[BSONDocument], but what I'm surprised is that I have an implicit conversion in scope. So I would have expected it to return an Option[User]!
回答1:
You can have a look at .findAndUpdate and to FindAndModifyResult which provides a .result
operation to get the result according available BSON readers.
val person: Future[Option[AType]] = collection.findAndUpdate(
BSONDocument("name" -> "James"),
BSONDocument("$set" -> BSONDocument("age" -> 17)),
fetchNewObject = true).map(_.result[AType])
回答2:
I just spent some time looking for play-reactivemongo
equivalent . Maybe this example help somebody in future.
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])
}
}
来源:https://stackoverflow.com/questions/33307215/reactivemongo-findandmodify-clarification