【问题标题】:Play 2.1 and reactivemongo 0.8 count documents播放 2.1 和 reactivemongo 0.8 计数文档
【发布时间】:2013-08-04 14:04:42
【问题描述】:

我有通过Reactivemongo 0.8 plugin 使用MongoDB 的Play 2.1 应用程序。在我的应用程序中,我使用 here 描述的方法而不使用模型

我有一个方法可以从 mongodb 返回所有文档,其中“type”等于函数 getTypeAll 中的 getType 参数,例如 {"type": "computer"},它工作正常。

def getTypeAll(getType: String) = Action {

val validatedType = getType.replaceAll("-"," ")
val q = QueryBuilder().query(toType.writes(validatedType))

Async {

 val f = collection.find[JsValue](q)

 f.toList.map{ 

  jsonp => 


  Ok( Json.toJson(jsonp) )   

    }
  }
}

toType 写为val toType = OWrites[String]{ s => Json.obj("type" -> s) },val 集合定义为lazy val collection = db("mycollection")

问题是我无法编写方法来获取“类型”等于相同参数的文档计数。

def countTypeAll(getType: String) = Action {

}

并以 json 格式返回,例如 {"typecount": 45}

我正在查看我找到的每个示例,但没有成功。我想我想要的是val c = collection.find[JsValue](q).count()

但它给出了错误提示 value size is not a member of reactivemongo.api.DefaultCollection

谁能告诉我如何计算元素值等于指定值的所有文档?

【问题讨论】:

    标签: json mongodb playframework playframework-2.1 reactivemongo


    【解决方案1】:

    使用 ReactiveMongo 0.8,您必须使用 Count 命令来实现。

    val futureCount = db.command(Count(collection.name, Some(BSONDocument("type" -> BSONString(s)))))
    futureCount.map { count => // count is an Int
      // do some stuff
    }
    

    虽然没有办法直接给它一个 JSON 文档。但是,如果您不想自己编写 BSONDocument,则可以将您的 JSON 文档显式转换为 BSONDocument

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-12
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 1970-01-01
      相关资源
      最近更新 更多