I have a problematic mongo query. Problematic because it takes 10-12seconds and that's is why I am looking for a different implementation.
The query is trying to perform a count of how many items are in the collection. I'm sure there is a better way to perform the count.
Current implementation:
def count(criteria: Option[JsObject], skip: Int, limit: Option[Int]): Future[Long] =
(for {
col <- collection
counted <- col.count(
selector = criteria,
limit = limit,
skip = skip,
hint = None,
readConcern = ReadConcern.Majority
)
} yield counted) recoverWith {
case error =>
logger.error(
s"failed to count by [${criteria.getOrElse(JsObject.empty)}]" +
s" with error: [${error.getMessage}]"
, error)
Future.failed(MongoExceptionBuilder.buildError(error))
}
I've gone through documentation and I found aggregateWith command that could cooperate with the count function. I tried to implement it on myself but I failed. http://reactivemongo.org/releases/0.1x/documentation/advanced-topics/aggregation.html#count
def count(criteria: Option[JsObject], skip: Int, limit: Option[Int]): Future[Long] =
(for {
col <- collection
counted <- col.aggregateWith[Long]() { framework =>
import framework.{Count, Group, Match}
(Match(criteria.getOrElse(JsObject.empty)),List(Count("count")))
}.head
} yield counted) recoverWith {
case error =>
logger.error(
s"failed to count by [${criteria.getOrElse(JsObject.empty)}]" +
s" with error: [${error.getMessage}]"
, error)
Future.failed(MongoExceptionBuilder.buildError(error))
}
The error I see:
lt-dispatcher-4 c.i.d.c.c.m.PlayerProfileDAOapplyOrElse(line:95) failed to count by [{}] with error: [JsResultException(errors:List((,List(JsonValidationError(List(error.expected.jsnumber),WrappedArray())))))] play.api.libs.json.JsResultException: JsResultException(errors:List((,List(JsonValidationError(List(error.expected.jsnumber),WrappedArray())))))