llu*_*mpu 2 json mongodb playframework playframework-2.1 reactivemongo
我有使用MongoDBvia的Play 2.1应用程序Reactivemongo 0.8 plugin.在我的应用程序中,我使用此处描述的aproach 而不使用模型
我有从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) )
}
}
}
Run Code Online (Sandbox Code Playgroud)
toType写为,val toType = OWrites[String]{ s => Json.obj("type" -> s) }而val集合定义为lazy val collection = db("mycollection")
问题是我无法编写方法来获取"type"等于相同参数的文档的计数.
def countTypeAll(getType: String) = Action {
}
Run Code Online (Sandbox Code Playgroud)
并将其作为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
}
Run Code Online (Sandbox Code Playgroud)
但是没有办法直接给它一个JSON文档.但是,BSONDocument如果您不想自己编写BSONDocument ,则可以将JSON文档明确转换为.