Python MongoDB - insert_many Query
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 to pass 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 with predefined _id values into a collection.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["GFG"]
collection = db["Student"]
# List of student documents to insert
students = [
{ "_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 collection
collection.insert_many(students)
Output:

Example 2:
In this example _id is not provided, it is allocated automatically by MongoDB.
from pymongo import MongoClient
# Connect to MongoDB
myclient = MongoClient("mongodb://localhost:27017/")
# Access the database and collection
db = myclient["GFG"]
collection = db["Geeks"]
# List of documents to be inserted
mylist = [
{"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 document
collection.insert_many(mylist)
Output

Related Articles: