我的MongoDB数据库中有一个集合,包括几个键。现在我想用一个新的字段来更新这个集合。到目前为止,我得到的是:
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(命令)给了我一个OptionBSONDocument,但我感到惊讶的是,我的作用域有一个隐式转换。所以我希望它能返回一个OptionUser!
发布于 2015-10-24 14:28:49
您可以查看.findAndUpdate和FindAndModifyResult,后者提供了一个.result操作来根据可用的BSON读取器获得结果。
val person: Future[Option[AType]] = collection.findAndUpdate(
BSONDocument("name" -> "James"),
BSONDocument("$set" -> BSONDocument("age" -> 17)),
fetchNewObject = true).map(_.result[AType])发布于 2017-02-21 09:33:40
我只是花了一些时间寻找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])
}
}https://stackoverflow.com/questions/33307215
复制相似问题