In MongoDB,insert_many() method is used to insert multiple documents into a collection at once. When working with Python, this operation is performed using the PyMongo library.
Instead of inserting documents one by one with insert_one(), insert_many() allows developers topass a list of dictionaries, where each dictionary represents a document. This is a more efficient and cleaner approach when inserting bulk data into MongoDB.
Syntax
collection.insert_many(documents, ordered=True, bypass_document_validation=False, session=None, comment=None)
Parameters:
- documents (Required): A list of documents (dictionaries) to insert..
- ordered (Optional, default=True): If True, stops inserting if one fails. If False, tries to insert all.
- bypass_document_validation (Optional, default=False): If True, skips any validation rules.
- session (Optional): Used for advanced tasks like transactions.
- comment (Optional): Adds a note to the operation (from PyMongo v4.1).
Now, Let's explore some Examples:
Example 1:
In the below code, multiple student records are inserted withpredefined _id values into a collection.
PythonfrompymongoimportMongoClientclient=MongoClient("mongodb://localhost:27017/")db=client["GFG"]collection=db["Student"]# List of student documents to insertstudents=[{"_id":1,"name":"Vishwash","roll_no":"1001","branch":"CSE"},{"_id":2,"name":"Vishesh","roll_no":"1002","branch":"IT"},{"_id":3,"name":"Shivam","roll_no":"1003","branch":"ME"},{"_id":4,"name":"Yash","roll_no":"1004","branch":"ECE"}]# Inserting the documents into the collectioncollection.insert_many(students)
Output:
Snapshot of Terminal showing Output of Insertion with _id providedExample 2:
In this example_id is not provided, it is allocated automatically by MongoDB.
PythonfrompymongoimportMongoClient# Connect to MongoDBmyclient=MongoClient("mongodb://localhost:27017/")# Access the database and collectiondb=myclient["GFG"]collection=db["Geeks"]# List of documents to be insertedmylist=[{"Manufacturer":"Honda","Model":"City","Color":"Black"},{"Manufacturer":"Tata","Model":"Altroz","Color":"Golden"},{"Manufacturer":"Honda","Model":"Civic","Color":"Red"},{"Manufacturer":"Hyundai","Model":"i20","Color":"White"},{"Manufacturer":"Maruti","Model":"Swift","Color":"Blue"},]# _id is not specified; MongoDB will assign unique ObjectId to each documentcollection.insert_many(mylist)
Output
Snapshot of Terminal showing ouput of Insertion without _idRelated Articles: