Step 1: Start MongoDB Shell
Open your terminal.
Run the mongo command to start the MongoDB shell:
Step 2: Switch to a Database
To switch to a specific database, use the use command followed by the name of the database:
Replace mydatabase with the name of your database.
Step 3: Show Databases
To show all databases available on the MongoDB server, run the following command:
This command will list all databases, including empty databases.
Step 4: Show Collections
After switching to a database, you can list all collections within that database using the show collections command:
This command will display all collections present in the current database.
Step 5: Show Data from a Collection
To display all documents (data) in a collection, use the db.collectionName.find() method. Replace collectionName with the name of your collection:
For example, to display all documents in a collection named users:
You can also apply query criteria to filter the results. For example, to find documents where the age field is greater than 18:
Step 6: Insert Documents into a Collection
To insert documents into a collection, use the db.collectionName.insertOne() or db.collectionName.insertMany() methods.
For example, to insert a single document into a collection named users:
To insert multiple documents into a collection:
{ name: “Alice”, age: 25 },
{ name: “Bob”, age: 35 }
])
Step 7: Update Documents in a Collection
To update documents in a collection, use the db.collectionName.updateOne() or db.collectionName.updateMany() methods.
For example, to update a single document in the users collection:
To update multiple documents:
Step 8: Delete Documents from a Collection
To delete documents from a collection, use the db.collectionName.deleteOne() or db.collectionName.deleteMany() methods.
For example, to delete a single document from the users collection:
To delete multiple documents:
Step 9: Exit MongoDB Shell
To exit the MongoDB shell, type exit and press Enter:
These commands cover the basic CRUD operations (Create, Read, Update, Delete) in MongoDB from the shell. Adjust the database, collection names, and query criteria as needed for your specific use case.