Reputation: 109
I'm sure this is really simple to do, but how do you sort by alphabetical (preferably a natural sort) in mongo w/ PHP? This is what I have right now:
$data->sort(array('title' => 1));
And it's not returning the array in alphabetical order. Am I missing something?!
Upvotes: 1
Views: 1990
Reputation: 306
actually this should sort in A-Za-z order, which is related to how MongoDB works with the indexes. You can have a look at the ticket: https://jira.mongodb.org/browse/SERVER-90 which is about the indexing issue. (see: https://jira.mongodb.org/browse/SERVER-105 for the specific ticket, which just references back to 90).
In the code example Eliot suggests to do something like: { name : { real : "Eliot" , sort : "eliot" } } which basically means you have a second field which you use only for the sorting, that contains the string you want to sort by all lowercase.
Sadly, until this ticket is fixed all solutions are just workarrounds, but Eliots solution allows you to sort and only retrieve a part of the set, opposed to retrieving the whole set and sorting by php
Upvotes: 1
Reputation: 1277
I am new to mongodb. But from what I understand about it is that less work should be done in mongodb and more work should be done in application. Its why mongodb can hit high speeds, simply because it is not trying to be an application its self like an RDMS. I think you will need to index the collection tho. just use ensureIndex(array('title' => 1));
Upvotes: 0