2

我有使用MongoDBvia的 Play 2.1 应用程序Reactivemongo 0.8 plugin。在我的应用程序中,我使用此处描述的 方法而不使用模型

我有从 mongodb 返回所有文档的方法,其中“类型”等于函数 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

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

4

1 回答 1

5

使用 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但是,如果您不想自己编写 BSONDocument ,则可以将您的 JSON 文档显式转换为。

于 2013-08-04T23:12:48.457 回答