1

I am trying to sort my mongodb query according to the occurence of a string in one of its fields (an array). So given this example dataset:

id | hits | categories
------------------------------
1  | 18   | ['sports']
2  | 12   | ['sports', 'news']
3  | 22   | []
4  | 20   | ['news']

I would like to make a query like this one ($includes is obviously a made-up keyword):

Records.find({}, {sort: {$includes: {categories: 'news'}, hits: -1});

Which would give me the resulting output:

id | hits | categories
------------------------------
4  | 20   | ['news']
2  | 12   | ['sports', 'news']
3  | 22   | []
1  | 18   | ['sports']

Is there a simple way to do that?

SylvainB
  • 4,765
  • 2
  • 26
  • 39
  • You can do this by adding weights to the words in the aggregation framework by using conditions ( http://stackoverflow.com/questions/21861150/weightning-documents-to-create-sort-criteria-in-mongodb like that ) but I would strongly advise against it – Sammaye Jul 15 '14 at 13:11
  • @Sammaye Why would you advise against it? – Philipp Jul 15 '14 at 13:44
  • I don't even think aggregate can be used in a meteor publication... so I don't know if it is very worth the investigation – SylvainB Jul 15 '14 at 13:50
  • @Philipp Supeeeer slow way of doing it. You will be sorting without an index, but there is no better – Sammaye Jul 15 '14 at 14:06

0 Answers0