Skip to content

Commit 84d8d2f

Browse files
author
Mike Dirolf
committed
distinct helper - Collection.distinct
1 parent d84aef5 commit 84d8d2f

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

pymongo/collection.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,19 @@ def rename(self, new_name):
686686

687687
self.__database.connection().admin._command(rename_command)
688688

689+
def distinct(self, key):
690+
"""Get a list of distinct values for `key` among all documents in this
691+
collection.
692+
693+
:Parameters:
694+
- `key`: name of key for which we want to get the distinct values
695+
"""
696+
if not isinstance(key, types.StringTypes):
697+
raise TypeError("key must be an instance of (str, unicode)")
698+
699+
command = SON([("distinct", self.__collection_name), ("key", key)])
700+
return self.__database._command(command)["values"]
701+
689702
def __iter__(self):
690703
return self
691704

test/test_collection.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -791,6 +791,32 @@ def test_cursor_timeout(self):
791791
list(self.db.test.find(timeout=False))
792792
list(self.db.test.find(timeout=True))
793793

794+
def test_distinct(self):
795+
self.db.drop_collection("test")
796+
797+
self.db.test.save({"a": 1})
798+
self.db.test.save({"a": 2})
799+
self.db.test.save({"a": 2})
800+
self.db.test.save({"a": 2})
801+
self.db.test.save({"a": 3})
802+
803+
distinct = self.db.test.distinct("a")
804+
distinct.sort()
805+
806+
self.assertEqual([1, 2, 3], distinct)
807+
808+
self.db.drop_collection("test")
809+
810+
self.db.test.save({"a": {"b": "a"}, "c": 12})
811+
self.db.test.save({"a": {"b": "b"}, "c": 12})
812+
self.db.test.save({"a": {"b": "c"}, "c": 12})
813+
self.db.test.save({"a": {"b": "c"}, "c": 12})
814+
815+
distinct = self.db.test.distinct("a.b")
816+
distinct.sort()
817+
818+
self.assertEqual(["a", "b", "c"], distinct)
819+
794820

795821
if __name__ == "__main__":
796822
unittest.main()

0 commit comments

Comments
 (0)