
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change Collection Name in MongoDB
Use use renameCollection() to change collection name in MongoDB. Following is the syntax
db.yourOldCollectionName.renameCollection("yourNewCollectionName");
Let us create a collection with documents. Following is the query
> db.savingInformationDemo.insertOne({"StudentName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cb44da629b87623db1b07") } > db.savingInformationDemo.insertOne({"StudentName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cb45da629b87623db1b08") } > db.savingInformationDemo.insertOne({"StudentName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cb461a629b87623db1b09") } > db.savingInformationDemo.insertOne({"StudentName":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cb465a629b87623db1b0a") }
Following is the query to display all documents from a collection with the help of find() method
> db.savingInformationDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9cb44da629b87623db1b07"), "StudentName" : "Larry" } { "_id" : ObjectId("5c9cb45da629b87623db1b08"), "StudentName" : "John" } { "_id" : ObjectId("5c9cb461a629b87623db1b09"), "StudentName" : "Mike" } { "_id" : ObjectId("5c9cb465a629b87623db1b0a"), "StudentName" : "Sam" }
Following is the query to change collection name in MongoDB
> db.savingInformationDemo.renameCollection("saveStudentInformation");
This will produce the following output
{ "ok" : 1 }
Following is the query to check the documents are displayed with new collection name or not
> db.saveStudentInformation.find();
This will produce the following output
{ "_id" : ObjectId("5c9cb44da629b87623db1b07"), "StudentName" : "Larry" } { "_id" : ObjectId("5c9cb45da629b87623db1b08"), "StudentName" : "John" } { "_id" : ObjectId("5c9cb461a629b87623db1b09"), "StudentName" : "Mike" } { "_id" : ObjectId("5c9cb465a629b87623db1b0a"), "StudentName" : "Sam" }
Advertisements