Is there a quick / optimal way to get a list of unique values ​​for a particular key?

I would like to get all the unique values ​​in the collection for a specific key in MongoDB. I can browse the entire collection to get them:

values = [] for item in collection.find(): if item['key'] in values: pass else: values.append(item) 

But this seems incredibly inefficient, as I have to check every record and cycle through the list every time (which slows down as the number of values ​​gets high). Alternatively, I can put all the values ​​in a list and then create a set (which, I think, is faster, although I have not yet tried to figure out how to check the speed):

 values = [] for item in collection.find(): values.append(item['key']) unique_values = set(values) 

Or with a list:

 unique_values = set([item['key'] for item in collection.find()]) 

But I wonder if there is a built-in function that would not require a loop through the entire collection (for example, if these values ​​are stored in hash tables or something else), or if there is a better way to get this.

+4
source share
2 answers

This method is distinct() . It returns an array (list) of different values ​​for a given key:

 unqiue_values = collection.distinct("key") 
+4
source

MongoDB has a built-in method for this problem:

 db.collection.distinct(FIELD) 
+1
source

All Articles