[英]Play 2.1 and reactivemongo 0.8 count documents
我有Play 2.1应用程序,它通过Reactivemongo 0.8 plugin
使用MongoDB
。 在我的应用程序中,我使用此处介绍的方法而不使用模型
我有从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 collection被定义为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
有人可以告诉我如何计算元素值等于指定值的所有文档吗?
使用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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.