How to Connect and Use Mongosh in VS Code via MongoDB Extension

MongoDB for VS Code

You can use MongoDB for VS Code to connect to MongoDB and interact with it using mongosh. Here’s a step-by-step guide:


1. Install MongoDB Extension for VS Code

  1. Open VS Code.

  2. Click on the Extensions tab (or press Ctrl+Shift+X).

  3. In the search bar, type "MongoDB for VS Code".

  4. Click Install on the MongoDB for VS Code extension.


2. Open the MongoDB Extension

  1. Click on the MongoDB icon on the Activity Bar (left sidebar in VS Code).

  2. Click "Connect".


3. Connect to MongoDB

  • If you have a local MongoDB server that provide daemon service, click localhost:27017 with right mouse and select connect>

  • Get MongoDB Server service on (start service) and then run mongod at command terminal.

    mongodb://localhost:27017
  • If you have a MongoDB Atlas cloud database, follow these steps:

    1. Select your database and click "Connect".

    2. Choose "Connect using MongoDB Compass" and copy the connection string.

    3. Paste the connection string in VS Code’s MongoDB extension.

    4. Replace <password> with your database password.


4. Open Mongosh in VS Code

  1. Open a new VS Code terminal (Ctrl+ ` on Windows/Linux or Cmd+ ` on macOS).

  2. Type:

    mongosh

    This will connect to your default MongoDB instance. Select Launch MongoDB Shell to open mongosh shell at the vscode terminal.


5. Run MongoDB Commands in VS Code

  • Show all databases:

    show dbs
  • Switch to a database:

    use myDatabase
  • Insert a document:

    db.users.insertOne({ name: "Alice", age: 30 })
  • Retrieve documents:

    db.users.find()
  • Update a document:

    db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })
  • Delete a document:

    sdb.users.deleteOne({ : "Alice" })

6. Using the MongoDB Playground (Optional)

  • Click "New MongoDB Playground" in the MongoDB extension.

  • Write MongoDB queries and click "Run All" to execute them.


7. Disconnect and Exit Mongosh

  • To exit the shell, type:

    exit
  • To disconnect from MongoDB in VS Code, click the disconnect icon in the MongoDB extension.


Now you can connect, query, and manage MongoDB databases inside VS Code using mongosh! 🚀

Last updated