Reputation: 58
So, I need to sort my collection on MongoDB by fields that are on an array of objects.
I have
"columns": [{
"kind": "FirstKind",
"descriptor": "Description1",
"data": "Data to be sorted"
},{
"kind": "SecondKind",
"descriptor": "Description2",
"data": "Data to be sorted"
}]
What I want to achieve is selecting "FirstKind" and "Description1" or "SecondKind" and "Description2" and sort the collection by the field data. I found a solution to do that on MongoDB, by doing:
db.getCollection('results').aggregate(
[{
"$match": {
"$and": [{
"columns.kind": "FirstKind"
}, {
"columns.descriptor": "Name"
}]
}
},{
"$sort": {
"columns.data": -1
}
},{
"$limit": 20
}]
)
My problem now is how to translate that to ReactiveMongo on Scala. I've been trying to understand this documentation: http://reactivemongo.org/releases/0.11/documentation/advanced-topics/aggregation.html but I'm really confused about it. Has anyone ever used aggregate with ReactiveMongo on Scala? Thanks!
Upvotes: 1
Views: 1911
Reputation: 8413
I agree, it is not the most straightforward thing in ReactiveMongo.
I have tried to translate your code into the ReactiveMongo aggregation query syntaxt below. However I haven't run it so you might need to tweak it a little.
val dao = reactiveMongoApi.db.collection[BSONCollection]("results")
import dao.BatchCommands.AggregationFramework._
dao.aggregate(
Match(BSONDocument(
"columns.kind" -> "FirstKind",
"columns.descriptor" -> "Name")),
List(
Sort(Descending("limit")),
Limit(20)))
Upvotes: 1