Skip to content

Commit baf53be

Browse files
Park Hyunwoobehackett
authored andcommitted
Add optional parameter for pymongo.database.collection_names to ignore system collections
1 parent 9de93d9 commit baf53be

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

pymongo/database.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -397,14 +397,19 @@ def command(self, command, value=1,
397397

398398
return result
399399

400-
def collection_names(self):
400+
def collection_names(self, include_system_collections=True):
401401
"""Get a list of all the collection names in this database.
402+
403+
:Parameters:
404+
- `include_system_collections` (optional): if ``False`` list
405+
will not include system collections (e.g ``system.indexes``)
402406
"""
403407
results = self["system.namespaces"].find(_must_use_master=True)
404408
names = [r["name"] for r in results]
405409
names = [n[len(self.__name) + 1:] for n in names
406-
if n.startswith(self.__name + ".")]
407-
names = [n for n in names if "$" not in n]
410+
if n.startswith(self.__name + ".") and "$" not in n]
411+
if not include_system_collections:
412+
names = [n for n in names if not n.startswith("system.")]
408413
return names
409414

410415
def drop_collection(self, name_or_collection):

test/test_database.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@ def test_collection_names(self):
114114
for coll in colls:
115115
self.assertTrue("$" not in coll)
116116

117+
colls_without_systems = db.collection_names(False)
118+
for coll in colls_without_systems:
119+
self.assertTrue(not coll.startswith("system."))
120+
117121
def test_drop_collection(self):
118122
db = Database(self.client, "pymongo_test")
119123

0 commit comments

Comments
 (0)