How to Insert Data in MongoDB (insertOne, insertMany)
1. Definition
In MongoDB, data is inserted into a collection using methods like insertOne() for a single document and insertMany() for multiple documents.
2. When to Use
- Use insertOne() when adding a single record
- Use insertMany() when inserting multiple records at once
- When storing user data, products, or orders
- When building APIs and backend systems
3. Where it is Used
- Inside MongoDB collections
- Backend applications (Node.js APIs)
- Database operations (CRUD)
- Real-time and scalable systems
4. Why We Use It
- To store new data in the database
- To handle user input and save records
- To manage application data efficiently
- Supports both single and bulk insertion
5. How It Works
- Data is inserted as documents into a collection
- MongoDB automatically creates _id for each document
- insertOne() inserts a single document
- insertMany() inserts multiple documents in one operation
Basic Syntax
// insertOne()
db.users.insertOne({
name: "Manaswini",
age: 22
});
// insertMany()
db.users.insertMany([
{ name: "John", age: 25 },
{ name: "Sara", age: 23 }
]);Real Example
// Single user
db.users.insertOne({
name: "Manaswini",
skills: ["React", "Node.js"]
});
// Multiple users
db.users.insertMany([
{ name: "Alex", role: "Developer" },
{ name: "Priya", role: "Designer" }
]);6. Explanation
- insertOne() adds a single document
- insertMany() adds multiple documents
- Each document gets a unique _id
- Efficient for storing large data sets
7. Advantages
- Simple and easy to use
- Supports bulk insertion
- High performance
- Flexible document structure
8. Disadvantages
- No strict validation by default
- Duplicate data may occur
- Error handling needed for bulk inserts
Interview Points
- insertOne() → inserts single document
- insertMany() → inserts multiple documents
- Automatically creates _id
- Part of CRUD operations (Create)