MongoDB Rename Collection

MongoDB Rename Collection

MongoDB Rename Collection

Renaming a collection in MongoDB allows you to change its name without losing any data. This guide explains how to rename a collection using MongoDB Shell, Node.js (Mongoose), and Compass.

1. Understanding renameCollection() in MongoDB

MongoDB provides the renameCollection() method to change a collection's name.

CommandDescription
db.collection.renameCollection("newName")Renames a collection to the specified new name.
{ dropTarget: true }Drops the target collection if a collection with the new name already exists.

2. Rename a Collection Using MongoDB Shell

A. Open MongoDB Shell

Start the MongoDB shell:

mongosh

Select the database that contains the collection:

use blogDB

B. Rename a Collection

To rename posts to articles:

db.posts.renameCollection("articles")

Response:

{ "ok": 1 }

This means the collection was successfully renamed.

C. Verify the Collection Name Change

show collections

Expected Output:

articles

D. Rename and Overwrite an Existing Collection

If articles already exists and you want to replace it, use:

db.posts.renameCollection("articles", { dropTarget: true })

Warning: This will delete the existing articles collection before renaming posts.

3. Rename a Collection Using Node.js (Mongoose)

A. Install Mongoose (If Not Installed)

npm install mongoose

B. Rename Collection Using a Script

Create renameCollection.js:

const mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/blogDB', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log("✅ Connected to MongoDB")) .catch(err => console.error("❌ Connection Error:", err)); async function renameCollection() { try { const db = mongoose.connection.db; await db.collection('posts').rename('articles'); console.log("✅ Collection renamed from 'posts' to 'articles'"); } catch (error) { console.log("❌ Error renaming collection:", error.message); } finally { mongoose.connection.close(); } } renameCollection();

Run the script:

node renameCollection.js

If successful, the console will display:

✅ Collection renamed from 'posts' to 'articles'

4. Rename a Collection Using Express.js API

A. Modify routes/postRoutes.js

const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); // PUT - Rename collection router.put('/rename', async (req, res) => { try { const db = mongoose.connection.db; await db.collection('posts').rename('articles'); res.json({ message: "✅ Collection renamed from 'posts' to 'articles'" }); } catch (error) { res.status(400).json({ message: "❌ Error renaming collection", error: error.message }); } }); module.exports = router;

B. Test the API (Using cURL or Postman)

curl -X PUT http://localhost:3000/api/posts/rename

Example Response:

{ "message": "✅ Collection renamed from 'posts' to 'articles'" }

5. Rename a Collection Using MongoDB Compass

If you prefer a graphical interface, use MongoDB Compass:

  1. Open MongoDB Compass and connect to your database.
  2. Navigate to the database (e.g., blogDB).
  3. Find the collection you want to rename (e.g., posts).
  4. Click the "..." (More Options) button next to the collection.
  5. Select Rename Collection, enter the new name (e.g., articles), and confirm.

The collection will be renamed without losing any data.

6. Summary

Renamed a collection using MongoDB Shell (renameCollection()).
Used Mongoose to rename a collection via a script.
Created an Express.js API to rename a collection dynamically.
Used MongoDB Compass for a GUI-based approach.

7. Next Steps

🔹 Ensure uniqueness when renaming to avoid conflicts.
🔹 Implement authentication to prevent unauthorized changes.
🔹 Backup collections before renaming (if needed).

Would you like help implementing backups 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