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.
source share