Insert Documents into a Collection
Learn how to insert documents into a MongoDB collection using insertOne() and insertMany(). This tutorial covers the syntax, hands-on examples, and best practices for adding data to your MongoDB database.
Focus: insert documents into a collection
You've built your database and your collection, but it's still empty. Inserting documents into a collection is the moment your MongoDB database comes alive — it's the first real write operation you'll perform, and getting it right sets the tone for every query, update, and delete that follows. In this lesson, you'll master the two core methods — insertOne() and insertMany() — understand their differences, and learn how to avoid the common pitfalls that trip up beginners.
The problem this lesson solves
Before you can query, update, or analyze data in MongoDB, you need data to work with. Manually creating documents in the mongo shell or through a GUI might work for a quick test, but in real applications you need a programmatic, reliable way to insert documents into a collection.
Imagine you're building a user registration system. Every new user who signs up needs to be saved to the database. If you don't know how to insert documents correctly, you'll end up with inconsistent data, duplicate records, or frustrated users because their data never made it to the database.
This lesson solves that problem by teaching you the exact syntax and best practices for inserting documents — both single documents and multiple documents in bulk. You'll learn how to handle success and failure, and how to avoid the classic mistakes that lead to silent data loss.
Core concept / mental model
Think of a MongoDB collection as a filing cabinet and documents as the files inside it. Each file is self-contained, with its own fields and data types — there's no rigid schema forcing every file to have the same pages. The insertOne() method is like adding one new file to the cabinet, and insertMany() is like dropping in a whole stack of files at once.
A document is a JSON-like structure (BSON, to be precise) that holds key-value pairs. Here's a simple example:
{
"name": "Ada Lovelace",
"email": "ada@example.com",
"age": 36
}
When you insert a document, MongoDB automatically adds an _id field if you don't provide one. This is a unique identifier for the document, and it's what makes each document distinct within a collection. You can think of _id as the label on the file — it's how MongoDB knows which file is which.
Key insight: MongoDB is schema-flexible, but that doesn't mean schema-less chaos. You still need to be intentional about the fields you insert to keep your data consistent.
How it works step by step
Inserting documents in MongoDB follows a simple, predictable flow:
- Connect to MongoDB — You need a connection to your MongoDB instance. This is typically done via a driver (e.g., PyMongo in Python) or the
mongoshshell. - Select the database and collection — Specify which database and collection you want to insert into. If they don't exist, MongoDB creates them on the fly.
- Build your document(s) — Define the data you want to insert as a Python dictionary or a BSON document in the shell.
- Call the insert method — Use
insert_one()for a single document orinsert_many()for a list of documents. - Check the result — MongoDB returns a result object that tells you whether the insert succeeded and what
_idwas assigned.
Let's break down each method.
Using insertOne() (or insert_one in PyMongo)
insertOne() inserts a single document into a collection. In PyMongo, the method is insert_one(). Here's the syntax:
from pymongo import MongoClient
# Connect to MongoDB (default localhost:27017)
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
users = db["users"]
# Define a document (a Python dictionary)
user_doc = {
"name": "Ada Lovelace",
"email": "ada@example.com",
"age": 36,
"hobbies": ["mathematics", "programming"]
}
# Insert the document and capture the result
result = users.insert_one(user_doc)
print("Inserted document ID:", result.inserted_id)
Expected output:
Inserted document ID: 60f7a1b2c3d4e5f6a7b8c9d0
The result.inserted_id gives you the _id that MongoDB assigned to the new document. If you provided your own _id in the document, it would return that value instead.
Using insertMany() (or insert_many in PyMongo)
When you need to insert multiple documents at once, insertMany() is far more efficient than looping and calling insertOne() repeatedly — each call has network overhead, so batching them into one operation saves time and resources.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
users = db["users"]
# A list of documents
new_users = [
{"name": "Alan Turing", "email": "alan@example.com", "age": 41},
{"name": "Grace Hopper", "email": "grace@example.com", "age": 85},
{"name": "Katherine Johnson", "email": "katherine@example.com", "age": 101}
]
result = users.insert_many(new_users)
print("Inserted IDs:", result.inserted_ids)
Expected output:
Inserted IDs: [ObjectId('...'), ObjectId('...'), ObjectId('...')]
Each document gets its own _id, and they're returned in the same order as the input list.
Inserting in the mongosh shell
You're not limited to Python — you can insert documents directly in the MongoDB shell (mongosh) using insertOne() and insertMany(). Here's an example:
db.users.insertOne({
name: "Ada Lovelace",
email: "ada@example.com",
age: 36
})
db.users.insertMany([
{ name: "Alan Turing", email: "alan@example.com", age: 41 },
{ name: "Grace Hopper", email: "grace@example.com", age: 85 }
])
The syntax is nearly identical, which makes it easy to switch between the shell and your application code.
Hands-on walkthrough
Let's put it all together in a practical exercise. You'll create a simple products collection and insert both a single product and a batch of products, then verify the insert worked.
Step 1: Set up your environment
Make sure you have MongoDB running locally and PyMongo installed:
pip install pymongo
Step 2: Insert a single product
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["shop"]
products = db["products"]
# Insert one product
telephone = {
"name": "Rotary Telephone",
"price": 49.99,
"in_stock": True,
"tags": ["vintage", "communication"]
}
result = products.insert_one(telephone)
print("Inserted product ID:", result.inserted_id)
Step 3: Insert multiple products
more_products = [
{"name": "Vinyl Record Player", "price": 199.99, "in_stock": True},
{"name": "Cassette Tape", "price": 9.99, "in_stock": False},
{"name": "Walkman", "price": 89.99, "in_stock": True}
]
result = products.insert_many(more_products)
print("Inserted IDs:", result.inserted_ids)
Step 4: Verify the data
for product in products.find():
print(product)
Expected output (IDs will vary):
{'_id': ObjectId('...'), 'name': 'Rotary Telephone', 'price': 49.99, 'in_stock': True, 'tags': ['vintage', 'communication']}
{'_id': ObjectId('...'), 'name': 'Vinyl Record Player', 'price': 199.99, 'in_stock': True}
{'_id': ObjectId('...'), 'name': 'Cassette Tape', 'price': 9.99, 'in_stock': False}
{'_id': ObjectId('...'), 'name': 'Walkman', 'price': 89.99, 'in_stock': True}
You've successfully inserted documents into a collection!
Compare options / when to choose what
The main comparison is between insertOne() and insertMany(). Here's a quick reference:
| Method | Use case | Pros | Cons |
|---|---|---|---|
insertOne() |
Inserting a single document | Simple, precise; you know exactly what you inserted | One network round-trip per insert; slow for bulk loading |
insertMany() |
Inserting multiple documents at once | Efficient, fewer round-trips; atomic by default | If one document fails, the whole batch may fail (unless you set ordered: false) |
Pro tip: Use
insertMany()whenever you have a list of documents to insert. It's faster and reduces chaos in your code. ReserveinsertOne()for truly single inserts, like a user signing up that you want to handle in isolation.
Another variation is using bulkWrite() for more complex operations that mix inserts, updates, and deletes. While insertMany() is perfect for pure inserts, bulkWrite() gives you flexibility when you need to perform a mix of operations in one shot.
Troubleshooting & edge cases
Even with a straightforward operation, things can go wrong. Here are common errors and how to fix them.
Duplicate _id
If you manually specify an _id that already exists in the collection, MongoDB throws a DuplicateKeyError.
# This will fail if the _id already exists
doc = {"_id": 1, "name": "Duplicate"}
try:
users.insert_one(doc)
except Exception as e:
print("Error:", e)
Fix: Let MongoDB auto-generate the _id, or ensure your custom IDs are unique.
insert_many() with ordered=False
By default, insert_many() is ordered — if one document fails, the rest are not inserted. You can change this with ordered=False to continue inserting even if some fail.
result = users.insert_many(docs, ordered=False)
This is useful when you're importing a large dataset and don't want one bad document to stop the whole import.
Document size limit
MongoDB has a maximum document size of 16MB. This includes all fields and nested arrays. If your document exceeds that, you'll get a DocumentTooLarge error.
Fix: Break your data into smaller documents, or redesign your schema to avoid storing large binary data (e.g., store images in GridFS instead).
Server connection issues
If you forget to start MongoDB, you'll get a ServerSelectionTimeoutError in PyMongo. Make sure MongoDB is running and the connection string is correct.
Pro tip: Always check the return value of
insert_one()orinsert_many()— the result object containsacknowledged(a boolean that confirms the write was acknowledged). If it'sFalse, something went wrong.
What you learned & what's next
You now understand how to insert documents into a collection using insertOne() and insertMany() in both PyMongo and the mongosh shell. You can insert single documents, bulk insert with lists, and handle common errors like duplicate keys and document size limits. You also learned when to prefer insertMany() over insertOne() for performance and efficiency.
You're ready to move on to the next step in your MongoDB journey: reading documents from a collection. The find() method is the natural next topic, and you'll use the documents you inserted in this lesson as the foundation for your queries. Happy coding!
Practice recap
Try a mini exercise on your own: create a books collection and insert five of your favorite books using insert_many(). Then, attempt to insert a book with a duplicate _id and see the error. Finally, insert a new book with insert_one() to confirm you can still insert after a failed batch.
Common mistakes
- Forgetting to handle the
DuplicateKeyErrorwhen inserting with a custom_idthat already exists in the collection. - Using
insert_many()withoutordered=Falsewhen you want to skip invalid documents and still insert the valid ones. - Assuming
insertOne()is as efficient asinsertMany()for bulk inserts — each call costs network round-trips, so always batch when possible. - Ignoring the
acknowledgedfield in the result object, which tells you whether the write was actually confirmed by the server.
Variations
- Use
bulkWrite()for mixed operations (insert, update, delete) in a single batch, giving you more control and atomicity options. - Insert documents using the
mongoshshell withdb.collection.insertOne()anddb.collection.insertMany()— great for quick testing and scripts. - Use PyMongo's
insert_many()with theordered=Falseparameter to continue inserting even when some documents fail validation.
Real-world use cases
- User registration and profile creation — new user data from a signup form is inserted into the
userscollection. - E-commerce order handling — when a customer places an order, the order details are inserted into the
orderscollection. - Log or event ingestion — bulk inserting application logs or telemetry events into a
logscollection for analysis.
Key takeaways
- Inserting documents is the first write operation you'll perform in MongoDB, and it's the foundation for all future queries.
- Use
insertOne()for single documents andinsertMany()for batches to improve performance and reduce network overhead. - MongoDB automatically adds an
_idfield if you don't provide one — and each document in a collection must have a unique_id. - Be aware of the 16MB document size limit and the default ordered behavior of
insertMany(). - Always check the result object for acknowledgements and potential errors, and handle
DuplicateKeyErrorgracefully.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.