CRUD Operations - Creating Documents
Now that you understand MongoDB's document structure and data types, let's dive into creating your first documents. In this lesson, you'll learn how to insert data into MongoDB collections using various methods.
Learning Goals:
- Use
insertOne()to add single documents - Use
insertMany()to add multiple documents - Understand write acknowledgment and error handling
- Learn best practices for document creation
Inserting Single Documents
The insertOne() method allows you to insert a single document into a collection. Let's start with a basic example:
// Insert a single user document
const result = await db.collection('users').insertOne({
name: "Alice Johnson",
email: "alice@example.com",
age: 28,
createdAt: new Date()
});
console.log(`Inserted document with _id: ${result.insertedId}`);
When you run this code, MongoDB automatically generates a unique _id field if you don't provide one. The returned result contains the insertedId which you can use for reference.
Inserting Multiple Documents
For inserting multiple documents at once, use insertMany():
// Insert multiple user documents
const users = [
{
name: "Bob Smith",
email: "bob@example.com",
age: 32,
status: "active"
},
{
name: "Carol Davis",
email: "carol@example.com",
age: 25,
status: "active"
},
{
name: "David Wilson",
email: "david@example.com",
age: 41,
status: "inactive"
}
];
const result = await db.collection('users').insertMany(users);
console.log(`Inserted ${result.insertedCount} documents`);
console.log('Inserted IDs:', result.insertedIds);
When inserting multiple documents, MongoDB performs a single bulk write operation which is more efficient than multiple individual inserts.
Custom Document IDs
While MongoDB automatically generates _id values, you can provide your own:
// Insert document with custom _id
await db.collection('products').insertOne({
_id: "prod-001",
name: "Laptop",
category: "Electronics",
price: 999.99,
inStock: true
});
Write Acknowledgment and Error Handling
MongoDB provides write acknowledgment to confirm successful operations. Let's look at proper error handling:
try {
const result = await db.collection('users').insertOne({
name: "Eve Brown",
email: "eve@example.com"
});
console.log('Insert successful:', result.acknowledged);
} catch (error) {
console.error('Insert failed:', error.message);
}
Always handle potential errors when performing write operations. Common issues include duplicate _id values, validation errors, or connection problems.
Ordered vs Unordered Inserts
When using insertMany(), you can control whether inserts stop on the first error or continue:
- Ordered (Default)
- Unordered
// Stops on first error
try {
await db.collection('users').insertMany([
{_id: 1, name: "User 1"},
{_id: 1, name: "User 2"}, // Duplicate _id - this will fail
{_id: 3, name: "User 3"} // This won't be executed
], { ordered: true });
} catch (error) {
console.log('Insert stopped due to error:', error.message);
}
// Continues despite errors
try {
const result = await db.collection('users').insertMany([
{_id: 1, name: "User 1"},
{_id: 1, name: "User 2"}, // Duplicate _id - this will fail
{_id: 3, name: "User 3"} // This will still be inserted
], { ordered: false });
console.log(`Inserted ${result.insertedCount} documents`);
} catch (error) {
// Error contains information about failed operations
console.log('Some inserts failed, but others succeeded');
}
Common Pitfalls
- Duplicate
_iderrors: Remember that_idmust be unique across the collection - Large batch sizes: When using
insertMany(), very large batches may exceed memory limits - Missing error handling: Always wrap insert operations in try-catch blocks
- Data type mismatches: Ensure your document fields match the expected data types
- Network timeouts: Consider timeout settings for large insert operations
Summary
In this lesson, you learned how to create documents in MongoDB using insertOne() for single documents and insertMany() for multiple documents. You explored write acknowledgment, error handling strategies, and the difference between ordered and unordered inserts. These fundamental operations form the "C" in CRUD and are essential for populating your databases with data.
Show quiz
-
What method would you use to insert a single document into a MongoDB collection?
- A)
insert() - B)
insertOne() - C)
addDocument() - D)
createOne()
- A)
-
What happens if you don't provide an
_idfield when inserting a document?- A) The insert operation fails
- B) MongoDB generates a unique
_idautomatically - C) The document is inserted without an
_idfield - D) A sequential number is assigned as
_id
-
In ordered
insertMany(), what happens when one document fails to insert?- A) All documents are inserted anyway
- B) Only the failed document is skipped
- C) The operation stops at the first error
- D) MongoDB retries the failed document
-
Which property of the result object tells you how many documents were successfully inserted?
- A)
insertedCount - B)
successCount - C)
documentsInserted - D)
count
- A)
-
What is the main advantage of using unordered inserts with
insertMany()?- A) Faster performance
- B) Continues inserting valid documents even if some fail
- C) Automatic retry of failed documents
- D) Better memory usage
Answers:
- B)
insertOne() - B) MongoDB generates a unique
_idautomatically - C) The operation stops at the first error
- A)
insertedCount - B) Continues inserting valid documents even if some fail