How to use MongoDB Shell

how to use MongoDB Shell (mongosh) at the command terminal:

1. Start MongoDB Shell

If MongoDB is running, open your terminal or command prompt and type:

mongosh

This connects to the local MongoDB instance (mongodb://localhost:27017 by default).


2. Check the MongoDB Version

After launching mongosh, you can verify the version:

db.version()

3. Show Available Databases

To list all databases:

show dbs

4. Create or Switch to a Database

To create or switch to a database (testDB in this case):

use testDB

5. Create a Collection and Insert Documents

Collections in MongoDB are equivalent to tables in SQL.

Insert a Single Document

db.users.insertOne({ name: "Alice", age: 28, city: "New York" })

Insert Multiple Documents

sdb.users.insertMan([
  { name: "Bob", age: 34, city: "Chicago" },
  { name: "Charlie", age: 29, city: "San Francisco" }
])

6. Retrieve Data

Find All Documents

sdb.users.find()

Find a Specific Document

db.users.findOne({ name: "Alice" })

Find Documents with Filtering

db.users.find({ age: { $gt: 30 } })  // Finds users older than 30

7. Update Documents

Update a Single Document

db.users.updateOne({ name: "Alice" }, { $set: { age: 29 } })

Update Multiple Documents

db.users.updateMany({ city: "Chicago" }, { $set: { city: "New York" } })

8. Delete Documents

Delete One Document

db.users.deleteOne({ name: "Charlie" })

Delete Multiple Documents

db.users.deleteMany({ age: { $lt: 30 } })

9. Drop a Collection

To delete the users collection:

db.users.drop()

10. Exit MongoDB Shell

To exit mongosh:

exit

Final Output Example

After executing db.users.find().pretty(), you might see:

[
  {
    "_id": ObjectId("65ab45f12345"),
    "name": "Alice",
    "age": 29,
    "city": "New York"
  },
  {
    "_id": ObjectId("65ab45f12346"),
    "name": "Bob",
    "age": 34,
    "city": "New York"
  }
]

This example covers the basic CRUD (Create, Read, Update, Delete) operations in MongoDB Shell (mongosh). 🚀

Last updated