Insert Documents

Insert Documents into MongoDB

Inserting data is the first step in any app. MongoDB provides clean methods for adding data. You can insert a single document or multiple at once.

Inserting One Document

To add one record, use insertOne(). You pass a single JSON object as the argument. MongoDB will automatically generate an _id field.

The _id Field

Every document must have a unique _id. If you don't provide one, MongoDB creates an ObjectId. It ensures primary key uniqueness globally.

Inserting Multiple Documents

To add many records, use insertMany(). You pass an array of JSON objects. It is heavily optimized for bulk operations.

Ordered vs Unordered

By default, bulk inserts are ordered. If one document fails, the process stops. You can turn off ordered inserts to continue anyway.

Insert Examples:

// Inserting a single document
db.users.insertOne({ 
  name: "John Doe", 
  age: 30 
});

// Inserting multiple documents db.users.insertMany([ { name: "Jane", age: 25 }, { name: "Bob", age: 40 } ]);

Acknowledgment

When an insert finishes, it returns an acknowledgment. This tells you if the operation succeeded. It also provides the newly created _id values.

Nested Documents

You can insert complex, nested data. A document can contain objects inside objects. It can also contain arrays of data.

Best Practices

Avoid massive arrays inside single documents. Keep your document size under the 16MB limit. Use bulk operations when importing large datasets.

Summary

Inserting is straightforward and fast. Use insertOne() or insertMany(). Rely on MongoDB to handle your _id keys automatically.

Exercise

Which method is most efficient for adding 100 documents at the same time?