Using the MongoDB Command-Line Interface (CLI)
Introduction
The MongoDB Command-Line Interface (CLI) provides a powerful way to interact with your MongoDB databases. This guide covers the basics of using the MongoDB CLI, including connecting to a database, performing CRUD operations, and managing your MongoDB deployment.
Connecting to MongoDB
Step 1: Start the MongoDB Server
Ensure that the MongoDB server is running on your local machine or remote server:
Example: Starting the MongoDB Server
sudo systemctl start mongod
Step 2: Open the MongoDB Shell
Open a terminal and start the MongoDB shell by running the following command:
Example: Opening the MongoDB Shell
mongo
This command connects to the MongoDB server running on the default host (localhost) and port (27017).
Basic Commands
Show Databases
To list all databases on the MongoDB server, use the following command:
Example: Showing Databases
show dbs
Switch Database
To switch to a specific database, use the use
command:
Example: Switching Database
use myDatabase
Show Collections
To list all collections in the current database, use the following command:
Example: Showing Collections
show collections
CRUD Operations
Create
To insert a document into a collection, use the insertOne
method:
Example: Inserting a Document
db.myCollection.insertOne({ name: "John Doe", age: 30, email: "john.doe@example.com" })
Read
To find documents in a collection, use the find
method:
Example: Finding a Document
db.myCollection.find({ name: "John Doe" })
Update
To update a document in a collection, use the updateOne
method:
Example: Updating a Document
db.myCollection.updateOne({ name: "John Doe" }, { $set: { age: 31 } })
Delete
To delete a document from a collection, use the deleteOne
method:
Example: Deleting a Document
db.myCollection.deleteOne({ name: "John Doe" })
Database Management
Create a Database
To create a new database, switch to the database and insert a document into a collection:
Example: Creating a Database
use newDatabase db.newCollection.insertOne({ name: "Example" })
Drop a Database
To drop a database, switch to the database and use the dropDatabase
method:
Example: Dropping a Database
use myDatabase db.dropDatabase()
Drop a Collection
To drop a collection, use the drop
method:
Example: Dropping a Collection
db.myCollection.drop()
Conclusion
The MongoDB CLI provides a versatile and efficient way to interact with your MongoDB databases. By mastering the basic commands and CRUD operations, you can effectively manage your MongoDB deployment and perform a wide range of tasks from the command line.