Unique values of a field


#1

Is there a way to fetch the unique values of a field in a given type?

I don’t want do something like the following, because it means I may fetch thousands of rows while I’m just looking for 3 to 5 unique values:

SomeType.fetch({include: 'somefield', limit: -1}).objs.map(x=>x.somefield).uniq()

#2

Have you tried SomeType.evaluate({projection:"unique(somefield)"}) ?


#3

You likely also need a limit: -1 in your evaluate right?


#4

Not really, unless he’s expecting >2000 unique values.


#5

According to the doc the limit is on the returned values, which in my case are very few.
Thanks for the hint, that works hundred times faster than my initial approach!


#6

As a follow-up it is also very easy to get a counter of distinct values for a specific field:

SomeType.evaluate({projection:“count(), somefield”, group: “somefield”, order: “descending(count())”, limit:-1})


#7

typename.evaluate({projection:“count(unique(somefield))”, limit:-1})