Skip to content

Instantly share code, notes, and snippets.

@yujikiriki
Created September 18, 2014 14:49
Show Gist options
  • Save yujikiriki/12a3dc9465aa50cd7fe6 to your computer and use it in GitHub Desktop.
Save yujikiriki/12a3dc9465aa50cd7fe6 to your computer and use it in GitHub Desktop.
ReactiveMongo aggregation pipeline example #2
collection.db.command(Aggregate(collection.name, Seq(
Match(toBSON(jsonQuery)).get.asInstanceOf[BSONDocument]),
Project(convertProjectionJsonForAggregate(projectionJson):_*),
Sort(convertSortJsonForAggregate(versionDescendingSort))
))) map { stream =>
stream.toList map { doc =>
toJSON(doc).asInstanceOf[JsObject]
}
}
def convertProjectionJsonForAggregate(projectionJson: JsObject): Seq[(String, Int)] = {
projectionJson.fields filter {
(kv: (String, JsValue)) => kv._2.isInstanceOf[JsNumber]
} map {
(kv: (String, JsValue)) => (kv._1, kv._2.as[Int])
}
}
def convertSortJsonForAggregate(sortJson: JsObject): Seq[SortOrder] = {
sortJson.fields filter {
(kv: (String, JsValue)) => kv._2.as[Int] == 1 || kv._2.as[Int] == -1
} map {
(kv: (String, JsValue)) => if (kv._2.as[Int] == 1) Ascending(kv._1) else Descending(kv._1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment