@@ -305,6 +305,7 @@ def create_collection(
305305 read_concern : Optional ["ReadConcern" ] = None ,
306306 session : Optional ["ClientSession" ] = None ,
307307 timeout : Optional [float ] = None ,
308+ check_exists : Optional [bool ] = True ,
308309 ** kwargs : Any ,
309310 ) -> Collection [_DocumentType ]:
310311 """Create a new :class:`~pymongo.collection.Collection` in this
@@ -336,6 +337,8 @@ def create_collection(
336337 :class:`~pymongo.collation.Collation`.
337338 - `session` (optional): a
338339 :class:`~pymongo.client_session.ClientSession`.
340+ - ``check_exists`` (optional): if True (the default), send a listCollections command to
341+ check if the collection already exists before creation.
339342 - `**kwargs` (optional): additional keyword arguments will
340343 be passed as options for the `create collection command`_
341344
@@ -402,7 +405,7 @@ def create_collection(
402405 enabling pre- and post-images.
403406
404407 .. versionchanged:: 4.2
405- Added the ``clusteredIndex`` and ``encryptedFields`` parameters.
408+ Added the ``check_exists``, `` clusteredIndex``, and ``encryptedFields`` parameters.
406409
407410 .. versionchanged:: 3.11
408411 This method is now supported inside multi-document transactions
@@ -441,8 +444,10 @@ def create_collection(
441444 with self .__client ._tmp_session (session ) as s :
442445 # Skip this check in a transaction where listCollections is not
443446 # supported.
444- if (not s or not s .in_transaction ) and name in self .list_collection_names (
445- filter = {"name" : name }, session = s
447+ if (
448+ check_exists
449+ and (not s or not s .in_transaction )
450+ and name in self .list_collection_names (filter = {"name" : name }, session = s )
446451 ):
447452 raise CollectionInvalid ("collection %s already exists" % name )
448453 return Collection (
0 commit comments