Is there a way to sort Mongo's results by nested collections?

advertisements

We're storing millions of Subscriber records within our Mongo setup. I've been tasked with putting a front end on the records, allowing them to be searched. My search query looks great, but the I need to be able to sort them and make them pageable. Our Mongo design is as such that the channel information is nested in an array. I tried to sort on "Channels.Address", because Email is our only channel that has an address, but it doesn't work that way. It returns my results in the same order whether or not I have it ascending or descending.

Our collection looks something like:

Subscriber:

{
  "_id" : "",
  "FirstName" : "Tester",
  "LastName" : "Tester",
  "Channels" : [{
      "_t" : "EmailChannel",
      "IsEnabled" : true,
      "Type" : 1,
      "Address" : "[email protected]"
    }, {
      "_t" : "SmsChannel",
      "IsEnabled" : true,
      "Type" : 2,
      "Number" : "88888888"
    }, {
      "_t" : "FaxChannel",
      "IsEnabled" : false,
      "Type" : 4,
      "Number" : null
    }]
}

My current idea is to write a MapReduce that returns what I need and search on that instead of this. But it seems like such a waste of space to do that. It's a heavily used table, so I can't use eval. Does anyone have any suggestions?


As far as i know, there is no way to sort a mongodb nested array.

You could do it on your own code with a C# sort, or you could try the Aggregation Framework http://docs.mongodb.org/manual/applications/aggregation/. You will need to "recreate" your project, unwinding your channels, sorting them, and reagroup. I think this will do the trick!