In MongoDB, documents are the basic units of data, similar to rows in a relational database. The insert operations allow you to add one or multiple documents to a collection.
Why Insert Documents in MongoDB?
- Dynamic Data Addition: MongoDB allows you to insert documents without a predefined schema.
- Scalability: Supports inserting large volumes of data efficiently.
- Flexibility: Each document can have a unique structure, making MongoDB ideal for unstructured data.
Key Features of MongoDB Insert Operations
- Schema-less: Documents in a collection can have different fields.
- Automatic
_id
: MongoDB automatically assigns a unique _id field to each document if not provided. - Batch Inserts: Multiple documents can be added at once using insertMany.
Prerequisites
- MongoDB Installed: Download MongoDB from mongodb.com.
- Node.js Installed: Download and install Node.js from nodejs.org.
- MongoDB Shell or Compass Installed: Use either for database management.
Method 1: Insert Documents Using MongoDB Shell
Step 1: Open the MongoDB Shell
Run the following command:
mongosh
Step 2: Switch to a Database
Select a database or create a new one:
use myDatabase
Step 3: Insert a Single Document
Use the insertOne
method to add a document to a collection:
db.users.insertOne({ name: 'Alice', age: 25, city: 'New York' });
Step 4: Insert Multiple Documents
Use the insertMany
method to add multiple documents:
db.users.insertMany([
{ name: 'Bob', age: 30, city: 'London' },
{ name: 'Charlie', age: 35, city: 'San Francisco' }
]);
Verify the Inserted Documents
View all documents in the users collection:
db.users.find()
Method 2: Insert Documents Using Node.js
Step 1: Install MongoDB Driver
Run the following command to install the MongoDB Node.js driver:
npm install mongodb
Step 2: Insert Documents in Node.js
Create a file named app.js and write the following code:
Insert a Single Document
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myDatabase';
async function main() {
try {
// Connect to MongoDB
await client.connect();
console.log('Connected successfully to MongoDB');
// Select the database and collection
const db = client.db(dbName);
const collection = db.collection('users');
// Insert a single document
const result = await collection.insertOne({ name: 'Alice', age: 25, city: 'New York' });
console.log('Document inserted with ID:', result.insertedId);
} catch (err) {
console.error('Error inserting document:', err);
} finally {
// Close the connection
await client.close();
}
}
main();
Insert Multiple Documents
async function insertManyDocuments() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Insert multiple documents
const result = await collection.insertMany([
{ name: 'Bob', age: 30, city: 'London' },
{ name: 'Charlie', age: 35, city: 'San Francisco' }
]);
console.log('Inserted documents count:', result.insertedCount);
} catch (err) {
console.error('Error inserting documents:', err);
} finally {
await client.close();
}
}
insertManyDocuments();
Method 3: Insert Documents Using MongoDB Compass
MongoDB Compass provides a graphical interface for inserting documents.
Step 1: Open MongoDB Compass
- Launch Compass and connect to your MongoDB server (mongodb://localhost:27017).
- Select your database or create a new one.
Step 2: Insert Documents
- Select a collection or create a new one.
- Click “Insert Document” to add a single document.
- Enter the JSON document (e.g., { name: ‘Emma’, age: 28, city: ‘Paris’ }).
- Save the document.
For multiple documents, use the “Import Data” feature to upload a JSON file.
Real-World Use Case
Imagine building a blog application. Each blog post can be stored as a document in the posts collection.
Example: Inserting Blog Posts
async function addBlogPost(title, author, content) {
try {
await client.connect();
const db = client.db('blog');
const collection = db.collection('posts');
// Insert a blog post
const result = await collection.insertOne({ title, author, content, createdAt: new Date() });
console.log('Blog post added with ID:', result.insertedId);
} catch (err) {
console.error('Error adding blog post:', err);
} finally {
await client.close();
}
}
// Example usage
addBlogPost('MongoDB Tutorial', 'John Doe', 'This is a tutorial about MongoDB.');