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
Open VS Code.
Click on the Extensions tab (or press
Ctrl+Shift+X
).In the search bar, type "MongoDB for VS Code".
Click Install on the MongoDB for VS Code extension.
2. Open the MongoDB Extension
Click on the MongoDB icon on the Activity Bar (left sidebar in VS Code).
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:
Go to MongoDB Atlas.
Select your database and click "Connect".
Choose "Connect using MongoDB Compass" and copy the connection string.
Paste the connection string in VS Code’s MongoDB extension.
Replace
<password>
with your database password.
4. Open Mongosh in VS Code
Open a new VS Code terminal (
Ctrl+
`
on Windows/Linux orCmd+
`
on macOS).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