1

I there a way to do ORDER BY FIELD in MongoDB?

In Mysql there is something like:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(priority, "core", "board", "other")

Can this be achieved in MongoDB?

Similar query is answered in : How to ORDER BY FIELD VALUE in MongoDB

This uses aggregate function. What I want is without aggregate and something with in find.

Community
  • 1
  • 1
kiranramanna
  • 115
  • 1
  • 9
  • @JohnnyHK I am looking for something with out aggregate. – kiranramanna Mar 10 '16 at 03:56
  • No way to do it server-side with `find`, but you can do it client-side [like this](http://stackoverflow.com/a/32385762/1259510). – JohnnyHK Mar 10 '16 at 04:23
  • If that is so then this is not a duplicate question. question clearly states that I want is without aggregate and something with in find. which is not addressed anywhere in that duplicate link. – kiranramanna Apr 24 '16 at 09:26
  • Well you added that part in an edit after your question was marked a duplicate. But both questions clearly desire a `find` based solution (which doesn't exist server-side), so I don't see much point in reopening it unless you're looking for a client-side solution. – JohnnyHK Apr 24 '16 at 17:20

2 Answers2

3

Not currently. MongoDB only allows to sort a field by normal old ascending and descending order. You cannot give a custom sort order of priority or anything.

The closest would be to use the aggregation framework to assign values to the field to sort the way you want. Though this will not work well with large queries so I would not recommend it.

Sammaye
  • 43,242
  • 7
  • 104
  • 146
0

Yes MongoDB has "Order By" functionality it is achieved using sort() see below for two primitive examples of how to use:

db.collection.find({}).sort({"fieldName" : 1})

For descending sort use:

db.collection.find({}).sort({"fieldName" : -1})

Hughzi
  • 2,470
  • 1
  • 20
  • 30
  • 1
    That's not what he asked, this is very specific SQL syntax for sorting upon the values for the field, not the field itself – Sammaye Mar 09 '16 at 17:18
  • @Sammaye you can use sort to achieve a similar functionality i believe. I do not come from an SQL background but as i understand docs.mongodb.org/manual/tutorial/sort-results-with-indexes (scroll to using sort on multiple fields) will yield the same or similar results. let me know your thoughts and i will update my answer to match. Thanks it seems this question keeps on giving. – Hughzi Mar 10 '16 at 09:35
  • Not really. He is not sorting alphabetically there as such MongoDB simply cannot do that sever-side, i.e. he is sorting by c over b – Sammaye Mar 10 '16 at 10:20