Basic Commands of MongoDB

Starting MongoDB

To start MongoDB using Homebrew, run this command:

brew services start mongodb-community@8.0


Once started, enter the MongoDB shell by typing:

mongosh


Working with Databases

Create a New Database

To create or switch to a database, use:

use college
If the database doesn’t exist, it will be created automatically.


Show All Databases

show dbs


Working with Collections

Create Collections

db.createCollection("students")
db.createCollection("department")


Insert Data into Collection

Let’s insert some student records into the students collection:

db.students.insertOne({ name: "anil", age: 17, email: "anil@test.com" })
db.students.insertOne({ name: "sam", age: 19, email: "sam@test.com" })


View Data in Collection

To see all entries in the students collection:

db.students.find()


Update Data in Collection

To update the age of a student named "sam":

db.students.updateOne({ name: "sam" }, { $set: { age: 15 } })


Delete Collection

To delete the entire students collection:

db.students.drop()


Delete the Entire Database

Make sure you are using the correct database and then run:

db.dropDatabase()