MongoDB Insert Document

MongoDB Insert Document

MongoDB Insert Document

Inserting documents into MongoDB is essential for storing data, such as blog posts on a post-based website. This guide explains how to insert data step by step using MongoDB Shell, Node.js, Express.js, and Mongoose.

1. Understanding MongoDB Insert Operations

MongoDB provides multiple methods for inserting documents:

MethodDescription
insertOne(document)Inserts a single document into a collection.
insertMany([document1, document2, ...])Inserts multiple documents at once.

2. Insert Documents Using MongoDB Shell

A. Open MongoDB Shell

First, open the MongoDB shell by running:

mongosh

Then, select a database (it will be created if it doesn't exist):

use blogDB

B. Insert a Single Document

To insert a single blog post into the posts collection:

db.posts.insertOne({ title: "MongoDB Guide", content: "This is an introduction to MongoDB.", author: "John Doe", category: "Database", createdAt: new Date() })

Response:

{ "acknowledged": true, "insertedId": "65d1234abcde67890fgh1234" }

C. Insert Multiple Documents

To insert multiple blog posts at once:

db.posts.insertMany([ { title: "Learning MongoDB", content: "MongoDB is a NoSQL database.", author: "Jane Doe", category: "Database", createdAt: new Date() }, { title: "NoSQL vs SQL", content: "Understanding the differences between NoSQL and SQL databases.", author: "John Smith", category: "Technology", createdAt: new Date() } ])

Response:

{ "acknowledged": true, "insertedIds": { "0": "65d5678xyz123456abcd5678", "1": "65d7890mnop456789qrst5678" } }

3. Insert Documents Using Node.js & Mongoose

A. Install Mongoose

If you haven't installed Mongoose, install it first:

npm install mongoose

B. Define the Blog Post Schema

Create models/Post.js:

const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: { type: String, required: true }, author: { type: String, required: true }, category: { type: String, required: true }, createdAt: { type: Date, default: Date.now } }); const Post = mongoose.model('Post', postSchema); module.exports = Post;

C. Connect to MongoDB

Modify server.js to connect to MongoDB:

const express = require('express'); const mongoose = require('mongoose'); const Post = require('./models/Post'); const app = express(); app.use(express.json()); mongoose.connect('mongodb://127.0.0.1:27017/blogDB', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log("✅ Connected to MongoDB")) .catch(err => console.error("❌ MongoDB Connection Error:", err)); app.listen(3000, () => console.log('🚀 Server running on port 3000'));

4. Create an API to Insert Documents

A. Insert a Single Post

Modify routes/postRoutes.js to create an API route:

const express = require('express'); const router = express.Router(); const Post = require('../models/Post'); // POST - Insert a single blog post router.post('/', async (req, res) => { try { const post = new Post(req.body); await post.save(); res.status(201).json(post); } catch (error) { res.status(400).json({ message: "❌ Error inserting post", error }); } }); module.exports = router;

Example Request (Using cURL or Postman)

curl -X POST http://localhost:3000/api/posts -H "Content-Type: application/json" -d '{ "title": "How to Use MongoDB", "content": "MongoDB is a document-based database.", "author": "Alice", "category": "Database" }'

Example Response:

{ "_id": "65d9876abcde12345mnop5678", "title": "How to Use MongoDB", "content": "MongoDB is a document-based database.", "author": "Alice", "category": "Database", "createdAt": "2025-02-02T15:00:00.000Z" }

B. Insert Multiple Blog Posts

Modify routes/postRoutes.js to support batch insertion:

// POST - Insert multiple blog posts router.post('/batch', async (req, res) => { try { const posts = await Post.insertMany(req.body); res.status(201).json(posts); } catch (error) { res.status(400).json({ message: "❌ Error inserting multiple posts", error }); } });

Example Request (Using cURL or Postman)

curl -X POST http://localhost:3000/api/posts/batch -H "Content-Type: application/json" -d '[ { "title": "MongoDB Transactions", "content": "Transactions in MongoDB ensure data consistency.", "author": "Bob", "category": "Database" }, { "title": "Scaling MongoDB", "content": "Sharding helps scale MongoDB.", "author": "Charlie", "category": "Technology" } ]'

Example Response:

[ { "_id": "65dabcd123efg456hij789klm", "title": "MongoDB Transactions", "content": "Transactions in MongoDB ensure data consistency.", "author": "Bob", "category": "Database", "createdAt": "2025-02-02T15:10:00.000Z" }, { "_id": "65dabcd987zyx654wvu321onm", "title": "Scaling MongoDB", "content": "Sharding helps scale MongoDB.", "author": "Charlie", "category": "Technology", "createdAt": "2025-02-02T15:10:05.000Z" } ]

5. Summary

Inserted documents using MongoDB Shell (insertOne, insertMany).
Created an Express.js API to insert documents into MongoDB.
Used Mongoose to define a schema and insert blog posts.

6. Next Steps

🔹 Implement Validation (e.g., required fields, length limits).
🔹 Use Transactions for Atomic Inserts.
🔹 Secure API Endpoints with Authentication.

Would you like help setting up validation or authentication? 

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close