1

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!

rethab
  • 7,170
  • 29
  • 46
elisoff
  • 58
  • 1
  • 8

1 Answers1

1

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)))
rethab
  • 7,170
  • 29
  • 46
  • so, in case of `find` you can user `.cursor[CaseClass]()` and then apply collect or anything else you need to do with the objects. How do you do something similar with `aggregate` because it seems like it does not have `cursor` – Shurik Agulyansky Jul 01 '16 at 16:17
  • You should have a look at the [API reference](http://reactivemongo.org/releases/0.11/api/index.html#reactivemongo.api.commands.AggregationFramework$AggregationResult). – cchantep Jul 01 '16 at 19:38
  • 2
    We did, and it does not make much sense – Shurik Agulyansky Jul 04 '16 at 19:35
  • What makes sense is that it indicates a `Cursor` can be used from an `AggregationResult`, if the aggregation was performed in this way. – cchantep Aug 09 '16 at 08:01