Create, Drop and Rename MongoDB Database and Collection using Command-Line
In this article, we shall see how to Create, Drop and Rename MongoDB Database or collection using Command-Line or mongo shell. We shall also see how to rename the Mongo collection using the C# code base.
Today in this article, we will cover below aspects,
Please open the command prompt or PowerShell and log in to your database using a connection string.
Login to MongoDB
mongo < Connection string>
Example
>mongo mongodb+***://****:***********/thecodebuzz-*****-personal?authSource=admin&replicaSet=xxxxxxx-0&readPreference=primary&ssl=true
The above commands will let you log in to your MongoDB database cluster.
List the existing Database
show dbs
The above command shows all databases available on the server.
use <DBName>
The above command sets the given database as the current database. Example ‘CarTitles‘.
This database becomes the primary database for all respective commands executed.
Drop the database from MongoDB
Below is the command to drop the database from MongoDB.
db.dropDatabase()
The current database gets dropped and user can see the success/failure of the commands.
The above shows successful operation with status as “OK” for the drop of the database from MongoDB database.
Create the database in MongoDB using Command Line
Creating a new database in MongoDB using Command Line is easy.
use <NewDBName>
Create new Collection in MongoDB
Let’s say, you want to create a new database “TestMongoDB” with a new collection “TheCodeBuzzData”.
Command
db.createCollection("Collection Name")
Example
> use TestMongoDB switched to db TestMongoDB > db.createCollection("TheCodeBuzzData") { "ok" : 1 } >
You can very much create a collection using implicit DDL operations like
InsertOne or Update or Replace supported methods.
Example – below command will create “myTestCollection” using insert methods.
db.myTestCollection.insertOne( { x: 1 } );
Once you execute the above commands successfully, commands create/add the new collections with the name ‘myTestCollection‘.
Drop Collection in MongoDB
Drop Collection in MongoDB can be performed by following the below query.
Command:
> db.<Collection Name>.drop()
Above command Drops a Collection Using Default Write Concern.
Example:
> db.TheCodeBuzzData.drop() { "ok" : 1 }
Dropping a collection with write concern,
The following operation drops TheCodeBuzzData collection in the current database using the 1
write concern,
> db.TheCodeBuzzData.drop({ writeConcern: { w: 1 } })
Rename MongoDB collection
Rename the MongoDB collection. Please see the below article for more details,
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.