获取reactivemongo findAndUpdate函数的返回值

时间:2016-02-22 07:55:09

标签: mongodb scala reactivemongo

我在mongo集合上调用findAndUpdate函数来增加一个计数器,我想得到计数器的值以供进一步使用。这是我的代码:

collection.findAndUpdate(
    BSONDocument("name" -> "counter"),
    BSONDocument("$inc" -> BSONDocument("count" -> 1)),
    fetchNewObject = true,
    upsert = true
).map{ e =>
    println("count = " + e.value.getAs[Int]("count"))
    //I want to do something with the count here
}

这不会编译,因为e.value.getAs[Int]("count")似乎是错误的。 编译错误是:

value getAs is not a member of Option[service.this.collection.BatchCommands.FindAndModifyCommand.pack.Document]

请劝告,谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

case class Person(name: String, count: Int)

object Helpers { 
  def increaseCount(collection: BSONCollection): Future[Option[Int]] = {
    import collection.BatchCommands.FindAndModifyCommand.FindAndModifyResult
    implicit val reader = Macros.reader[Person]

    val resultFut: Future[FindAndModifyResult] = collection.findAndUpdate(
      BSONDocument("name" -> "James"),
      BSONDocument("$inc" -> BSONDocument("count" -> 1)),
      fetchNewObject = true,
      upsert = true
    )

    val updatedCountOpt = resultFut.map { r =>
      r.result[Person].map { p =>
        p.count
      }
    }

    updatedCountOpt
  }
}