Insert an iterable of documents. >>> db.test.count_documents({}) 0 >>> result = db.test.insert_many([{'x': i} for i in range(2)]) >>> result.inserted_ids [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')] >>> db.t
(
self,
documents: Iterable[Union[_DocumentType, RawBSONDocument]],
ordered: bool = True,
bypass_document_validation: Optional[bool] = None,
session: Optional[ClientSession] = None,
comment: Optional[Any] = None,
)
| 901 | |
| 902 | @_csot.apply |
| 903 | def insert_many( |
| 904 | self, |
| 905 | documents: Iterable[Union[_DocumentType, RawBSONDocument]], |
| 906 | ordered: bool = True, |
| 907 | bypass_document_validation: Optional[bool] = None, |
| 908 | session: Optional[ClientSession] = None, |
| 909 | comment: Optional[Any] = None, |
| 910 | ) -> InsertManyResult: |
| 911 | """Insert an iterable of documents. |
| 912 | |
| 913 | >>> db.test.count_documents({}) |
| 914 | 0 |
| 915 | >>> result = db.test.insert_many([{'x': i} for i in range(2)]) |
| 916 | >>> result.inserted_ids |
| 917 | [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')] |
| 918 | >>> db.test.count_documents({}) |
| 919 | 2 |
| 920 | |
| 921 | :param documents: A iterable of documents to insert. |
| 922 | :param ordered: If ``True`` (the default) documents will be |
| 923 | inserted on the server serially, in the order provided. If an error |
| 924 | occurs all remaining inserts are aborted. If ``False``, documents |
| 925 | will be inserted on the server in arbitrary order, possibly in |
| 926 | parallel, and all document inserts will be attempted. |
| 927 | :param bypass_document_validation: (optional) If ``True``, allows the |
| 928 | write to opt-out of document level validation. Default is |
| 929 | ``False``. |
| 930 | :param session: a |
| 931 | :class:`~pymongo.client_session.ClientSession`. |
| 932 | :param comment: A user-provided comment to attach to this |
| 933 | command. |
| 934 | |
| 935 | :return: An instance of :class:`~pymongo.results.InsertManyResult`. |
| 936 | |
| 937 | .. seealso:: `Writes and ids <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/insert/#overview>`_ |
| 938 | |
| 939 | .. note:: `bypass_document_validation` requires server version |
| 940 | **>= 3.2** |
| 941 | |
| 942 | .. versionchanged:: 4.1 |
| 943 | Added ``comment`` parameter. |
| 944 | |
| 945 | .. versionchanged:: 3.6 |
| 946 | Added ``session`` parameter. |
| 947 | |
| 948 | .. versionchanged:: 3.2 |
| 949 | Added bypass_document_validation support |
| 950 | |
| 951 | .. versionadded:: 3.0 |
| 952 | """ |
| 953 | if ( |
| 954 | not isinstance(documents, abc.Iterable) |
| 955 | or isinstance(documents, abc.Mapping) |
| 956 | or not documents |
| 957 | ): |
| 958 | raise TypeError("documents must be a non-empty list") |
| 959 | inserted_ids: list[ObjectId] = [] |
| 960 |