MongoDB Insert Documents
Learn how to add new documents to your MongoDB collections
📝 Adding Data to MongoDB
Inserting documents is how you add new data to MongoDB collections. You can insert one document at a time or multiple documents in a single operation. Each document is stored as a JSON-like structure called BSON.
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mystore"]
collection = db["products"]
# Insert a single document
product = {"name": "Laptop", "price": 999, "category": "Electronics"}
result = collection.insert_one(product)
print(f"Inserted document with ID: {result.inserted_id}")
Insert Methods
Insert One
Add a single document
user = {"name": "John", "age": 25}
result = collection.insert_one(user)
print(result.inserted_id)
Insert Many
Add multiple documents
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 35}
]
result = collection.insert_many(users)
Auto ID
MongoDB creates unique _id automatically
# No need to specify _id
doc = {"title": "My Post"}
result = collection.insert_one(doc)
# MongoDB adds _id automatically
Return Info
Get confirmation of insertion
result = collection.insert_one(doc)
print(f"Success: {result.acknowledged}")
print(f"ID: {result.inserted_id}")
Insert One Document
Use insert_one() to add a single document to a collection
import pymongo
# Connect to database
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["school"]
students = db["students"]
# Create a student document
student = {
"name": "Emma Wilson",
"age": 20,
"grade": "A",
"subjects": ["Math", "Science"]
}
# Insert the document
result = students.insert_one(student)
print(f"Document inserted successfully!")
print(f"Document ID: {result.inserted_id}")
print(f"Acknowledged: {result.acknowledged}")
Insert Multiple Documents
Use insert_many() to add multiple documents at once
# Create multiple student documents
student_list = [
{"name": "John Doe", "age": 19, "grade": "B"},
{"name": "Jane Smith", "age": 21, "grade": "A"},
{"name": "Mike Johnson", "age": 20, "grade": "C"}
]
# Insert all documents
result = students.insert_many(student_list)
print(f"Inserted {len(result.inserted_ids)} documents")
print("Document IDs:")
for doc_id in result.inserted_ids:
print(f" - {doc_id}")
Custom Document ID
You can specify your own _id instead of using the auto-generated one
# Insert with custom ID
custom_student = {
"_id": "student_001",
"name": "Sarah Connor",
"age": 22,
"grade": "A+"
}
try:
result = students.insert_one(custom_student)
print(f"Inserted with custom ID: {result.inserted_id}")
except pymongo.errors.DuplicateKeyError:
print("Error: Document with this ID already exists!")
Practical Examples
Real-world scenarios for inserting documents
🔹 E-commerce Product
# Insert a product
product = {
"name": "Wireless Headphones",
"price": 79.99,
"category": "Electronics",
"in_stock": True,
"tags": ["wireless", "bluetooth", "music"]
}
products = db["products"]
result = products.insert_one(product)
print(f"Product added with ID: {result.inserted_id}")
🔹 Blog Post
from datetime import datetime
# Insert a blog post
post = {
"title": "Getting Started with MongoDB",
"author": "Tech Writer",
"content": "MongoDB is a great NoSQL database...",
"created_at": datetime.now(),
"views": 0,
"published": True
}
posts = db["posts"]
result = posts.insert_one(post)
print(f"Blog post published with ID: {result.inserted_id}")