# 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>&#x20;
* Get MongoDB Server service on (start service) and then  run mongod at command terminal.&#x20;

  ```arduino
  mongodb://localhost:27017
  ```
* If you have a **MongoDB Atlas cloud database**, follow these steps:
  1. **Go to** [MongoDB Atlas](https://cloud.mongodb.com/).
  2. Select your database and **click "Connect"**.
  3. Choose **"Connect using MongoDB Compass"** and copy the connection string.
  4. Paste the connection string in VS Code’s **MongoDB extension**.
  5. 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:

   ```sh
   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:

  ```sh
  show dbs
  ```
* Switch to a database:

  ```sh
  use myDatabase
  ```
* Insert a document:

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

  ```sh
  db.users.find()
  ```
* Update a document:

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

  ```sh
  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:

  ```sh
  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`! 🚀
