MCPcopy Create free account
hub / github.com/mongodb/mongo-python-driver / insert_one

Method insert_one

pymongo/asynchronous/collection.py:839–901  ·  view source on GitHub ↗

Insert a single document. >>> await db.test.count_documents({'x': 1}) 0 >>> result = await db.test.insert_one({'x': 1}) >>> result.inserted_id ObjectId('54f112defba522406c9cc208') >>> await db.test.find_one({'x': 1}) {'x': 1, '_i

(
        self,
        document: Union[_DocumentType, RawBSONDocument],
        bypass_document_validation: Optional[bool] = None,
        session: Optional[AsyncClientSession] = None,
        comment: Optional[Any] = None,
    )

Source from the content-addressed store, hash-verified

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

Callers 1

insert_data_keyMethod · 0.45

Calls 4

_insert_oneMethod · 0.95
ObjectIdClass · 0.90
InsertOneResultClass · 0.90
_write_concern_forMethod · 0.80

Tested by

no test coverage detected