Skip to main content

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-single.js
// 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.js
// 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);
tip

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:

custom-id.js
// 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:

error-handling.js
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);
}
warning

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-insert.js
// 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);
}

Common Pitfalls

  • Duplicate _id errors: Remember that _id must 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
  1. What method would you use to insert a single document into a MongoDB collection?

    • A) insert()
    • B) insertOne()
    • C) addDocument()
    • D) createOne()
  2. What happens if you don't provide an _id field when inserting a document?

    • A) The insert operation fails
    • B) MongoDB generates a unique _id automatically
    • C) The document is inserted without an _id field
    • D) A sequential number is assigned as _id
  3. 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
  4. Which property of the result object tells you how many documents were successfully inserted?

    • A) insertedCount
    • B) successCount
    • C) documentsInserted
    • D) count
  5. 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:

  1. B) insertOne()
  2. B) MongoDB generates a unique _id automatically
  3. C) The operation stops at the first error
  4. A) insertedCount
  5. B) Continues inserting valid documents even if some fail