Insert a single document. >>> db.test.count_documents({'x': 1}) 0 >>> result = db.test.insert_one({'x': 1}) >>> result.inserted_id ObjectId('54f112defba522406c9cc208') >>> db.test.find_one({'x': 1}) {'x': 1, '_id': ObjectId('54f1
(
self,
document: Union[_DocumentType, RawBSONDocument],
bypass_document_validation: Optional[bool] = None,
session: Optional[ClientSession] = None,
comment: Optional[Any] = None,
)
| 836 | return None |
| 837 | |
| 838 | def insert_one( |
| 839 | self, |
| 840 | document: Union[_DocumentType, RawBSONDocument], |
| 841 | bypass_document_validation: Optional[bool] = None, |
| 842 | session: Optional[ClientSession] = None, |
| 843 | comment: Optional[Any] = None, |
| 844 | ) -> InsertOneResult: |
| 845 | """Insert a single document. |
| 846 | |
| 847 | >>> db.test.count_documents({'x': 1}) |
| 848 | 0 |
| 849 | >>> result = db.test.insert_one({'x': 1}) |
| 850 | >>> result.inserted_id |
| 851 | ObjectId('54f112defba522406c9cc208') |
| 852 | >>> db.test.find_one({'x': 1}) |
| 853 | {'x': 1, '_id': ObjectId('54f112defba522406c9cc208')} |
| 854 | |
| 855 | :param document: The document to insert. Must be a mutable mapping |
| 856 | type. If the document does not have an _id field one will be |
| 857 | added automatically. |
| 858 | :param bypass_document_validation: (optional) If ``True``, allows the |
| 859 | write to opt-out of document level validation. Default is |
| 860 | ``False``. |
| 861 | :param session: a |
| 862 | :class:`~pymongo.client_session.ClientSession`. |
| 863 | :param comment: A user-provided comment to attach to this |
| 864 | command. |
| 865 | |
| 866 | :return: - An instance of :class:`~pymongo.results.InsertOneResult`. |
| 867 | |
| 868 | .. seealso:: `Writes and ids <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/insert/#overview>`_ |
| 869 | |
| 870 | .. note:: `bypass_document_validation` requires server version |
| 871 | **>= 3.2** |
| 872 | |
| 873 | .. versionchanged:: 4.1 |
| 874 | Added ``comment`` parameter. |
| 875 | |
| 876 | .. versionchanged:: 3.6 |
| 877 | Added ``session`` parameter. |
| 878 | |
| 879 | .. versionchanged:: 3.2 |
| 880 | Added bypass_document_validation support |
| 881 | |
| 882 | .. versionadded:: 3.0 |
| 883 | """ |
| 884 | common.validate_is_document_type("document", document) |
| 885 | if not (isinstance(document, RawBSONDocument) or "_id" in document): |
| 886 | document["_id"] = ObjectId() # type: ignore[index] |
| 887 | |
| 888 | write_concern = self._write_concern_for(session) |
| 889 | return InsertOneResult( |
| 890 | self._insert_one( |
| 891 | document, |
| 892 | ordered=True, |
| 893 | write_concern=write_concern, |
| 894 | op_id=None, |
| 895 | bypass_doc_val=bypass_document_validation, |