0

If I have a document like this

{'id': 123, 'keywords': {'keyword1': 3, 'keyword2': 8, 'keyword3': 2}}

Can I get a query result with keywords sorted by values, like

{'id': 123, 'keywords': {'keyword3': 2, 'keyword1': 3, 'keyword2': 8}}

Is there a built-in mongodb feature for doing this? Or I have to implement this in application level?

s7vr
  • 73,656
  • 11
  • 106
  • 127
Kyle
  • 379
  • 6
  • 17
  • 2
    I don't see a way to do with the dynamic fields you've. You can use aggregate if you were to change `keywords` to `[{'keyword': 3}, {'keyword': 8}, {'keyword': 2}]` http://stackoverflow.com/questions/15388127/mongodb-sort-inner-array – s7vr Apr 16 '17 at 01:53
  • Field order is rarely important; why do you want to do this? – JohnnyHK Apr 16 '17 at 02:03
  • Hi @JohnnyHK, the goal is to find out top/bottom Kth keywords. – Kyle Apr 16 '17 at 02:23
  • 1
    @Kyle Then you should probably use an array like Veeram suggests, but with objects in the array like `{keyword: 'keyword1', value: 3}`. – JohnnyHK Apr 16 '17 at 03:03
  • that's a good idea. I will give it a try. thanks! – Kyle Apr 16 '17 at 13:19
  • 1
    You can take a look at answer http://stackoverflow.com/questions/43558778/how-to-retrieve-distinct-keys-inside-an-object-in-mongodb/43559471#43559471 which makes use of new aggregation operator `$objectToArray` from 3.4.4 to convert from object from array without the need to update the data in the collection and then use the answer I mentioned in my previous comment for sorting. Only downside you can't use index if you don't update the collection. – s7vr Apr 22 '17 at 23:38

0 Answers0