【问题标题】:Get the return value of reactivemongo findAndUpdate function获取reactivemongo findAndUpdate函数的返回值
【发布时间】:2016-11-25 01:45:48
【问题描述】:

我在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]

请多多指教,谢谢!

【问题讨论】:

    标签: mongodb scala reactivemongo


    【解决方案1】:

    试试这个:

    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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-03
      • 1970-01-01
      • 2018-08-25
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2020-12-16
      相关资源
      最近更新 更多