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.
To add one record, use insertOne(). You pass a single JSON object as the argument. MongoDB will automatically generate an _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.
To add many records, use insertMany(). You pass an array of JSON objects. It is heavily optimized for bulk operations.
By default, bulk inserts are ordered. If one document fails, the process stops. You can turn off ordered inserts to continue anyway.
// 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 }
]);
When an insert finishes, it returns an acknowledgment. This tells you if the operation succeeded. It also provides the newly created _id values.
You can insert complex, nested data. A document can contain objects inside objects. It can also contain arrays of data.
Avoid massive arrays inside single documents. Keep your document size under the 16MB limit. Use bulk operations when importing large datasets.
Inserting is straightforward and fast. Use insertOne() or insertMany(). Rely on MongoDB to handle your _id keys automatically.
Which method is most efficient for adding 100 documents at the same time?