Python Tutorial
Python MongoDB - Insert
Add one document or many, and read back the generated _id.
Insert One Document
Pass a dictionary to insert_one. MongoDB adds a unique _id automatically if you do not supply one.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
customers = client["mydatabase"]["customers"]
doc = {"name": "John", "address": "Highway 37"}
result = customers.insert_one(doc)
print(result.inserted_id) # e.g. ObjectId('652f...')The _id Field
Every document has a unique _id. By default it is an ObjectId — a 12-byte value that also encodes its creation time. You may set your own _id instead (it must be unique).
customers.insert_one({"_id": 1, "name": "Amy"}) # custom id
# inserting another {"_id": 1} raises DuplicateKeyErrorInsert Many Documents
insert_many takes a list of dictionaries and returns all generated ids in order.
people = [
{"name": "Amy", "address": "Apple st 652"},
{"name": "Hannah","address": "Mountain 21"},
{"name": "Michael","address": "Valley 345"},
]
result = customers.insert_many(people)
print(result.inserted_ids) # list of ObjectIdsDocuments Can Have Different Fields
Because collections are schema-less, documents need not match. This flexibility is a core MongoDB feature.
customers.insert_many([
{"name": "Ann"}, # no address
{"name": "Ben", "address": "5th Ave", "vip": True}, # extra field
])Ordered vs Unordered Inserts
By default insert_many stops at the first error. Set ordered=False to keep inserting the valid documents and collect errors at the end.
from pymongo.errors import BulkWriteError
try:
customers.insert_many(docs, ordered=False)
except BulkWriteError as e:
print("Some inserts failed:", e.details["writeErrors"])Best Practices
- Use
insert_manyfor bulk writes — far faster than loopinginsert_one. - Let MongoDB generate
_idunless you have a natural unique key. - Use
ordered=Falsewhen partial success is acceptable. - Keep a consistent document shape even though it is not enforced.
Try It Yourself
Exercise 1: Insert three documents in a single call and print their ids.
Show solution
docs = [{"n": 1}, {"n": 2}, {"n": 3}]
result = coll.insert_many(docs)
print(result.inserted_ids)Exercise 2: If you do not supply _id, what does MongoDB do?
Show solution
It generates a unique ObjectId automatically.
📘 Real-World Deep Dive
Knowing <strong>MongoDB Insert (MongoDB)</strong> well is what turns MongoDB from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of MongoDB Insert that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from pymongo import MongoClient
from datetime import datetime, timezone
db = MongoClient().demo
doc = {"sensor": "temp-01", "value": 22.4, "ts": datetime.now(timezone.utc)}
res = db.readings.insert_one(doc)
print("inserted id:", res.inserted_id)Expected Output
(see source)Common mistakes
- Inserting a
dictwith embeddeddatetimeworks, but naivedatetime(without UTC) leads to subtle comparison bugs. - Queries with type-mismatched values silently return no results — cast at the boundary or use
bsoncodecs. find()returns a cursor — calllist(cursor)only once you intend to materialise results.- Treating MongoDB Insert as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Project only the fields you need:
collection.find({}, {"name": 1}). - Use
bulk_writeinstead of looping over single inserts / updates — order-of-magnitude faster. - Create indexes:
collection.create_index([("field", pymongo.ASCENDING)]). - When working with MongoDB, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.