This method is used to insert multiple entries in a collection or the database in MongoDB. The parameter of this method is a list that contains dictionaries of the data that we want to insert in the collection.
This method returns an instance of class “~pymongo.results.InsertManyResult” which has a “_id” field that holds the id of the inserted documents. If the document does not specify an “_id” field, then MongoDB will add the “_id” field to all the data in the list and assign a unique object id for the documents before inserting.
Syntax: collection.insert_many(documents, ordered=True, bypass_document_validation=False, session=None)
- ‘documents’ : A iterable of documents to insert.
- ‘ordered’ (optional): If “True” (the default) documents will be inserted on the server serially, in the order provided. If an error occurs all remaining inserts are aborted. If “False”, documents will be inserted on the server in arbitrary order, possibly in parallel, and all document inserts will be attempted.
- ‘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’.
Example 1: In this example _id is provided.
Example 2: In this example _id is not provided, it is allocated automatically by MongoDB.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course