Python MongoDB – insert_one Query
This is a method by which we can insert a single entry within the collection or the database in MongoDB. If the collection does not exist this method creates a new collection and insert the data into it. It takes a dictionary as a parameter containing the name and value of each field in the document you want to insert in the collection.
This method returns an instance of class “~pymongo.results.InsertOneResult” which has a “_id” field that holds the id of the inserted document. If the document does not specify an “_id” field, then MongoDB will add the “_id” field and assign a unique object id for the document before inserting.
collection.insert_one(document, bypass_document_validation=False, session=None, comment=None)
- ‘document’: The document to insert. Must be a mutable mapping type. If the document does not have an _id field one will be added automatically.
- ‘bypass_document_validation’ (optional): If “True”, allows the write to opt-out of document level validation. Default is “False”.
- ‘session’ (optional): A class ‘~pymongo.client_session.ClientSession’.
- ‘comment'(optional): A user-provided comment to attach to this command.
Sample database is as follows:
Example 2: Inserting multiple values
To insert multiple values, 2 Methods can be followed:
#1: Naive Method: Using for loop and insert_one
#2: Using insert_many method: This method can be used to insert multiple documents in a collection in MongoDB.
The insert_many method is explained briefly in the next tutorial.