Connecting to MongoDB
7 min read
Connecting: mongosh and Connection Strings
You can talk to MongoDB using mongosh (the interactive shell) or a language driver (Node.js, Python, etc.). Both use a connection string — a URI that encodes host, port, credentials, and database.
Using mongosh
js
// Connect to a local instance
mongosh
// Connect to a remote instance
mongosh "mongodb://localhost:27017/school"
// Connect to MongoDB Atlas
mongosh "mongodb+srv://user:pass@cluster0.abcde.mongodb.net/school"Node.js Driver
js
import { MongoClient } from "mongodb";
const uri = "mongodb+srv://user:pass@cluster0.abcde.mongodb.net/";
const client = new MongoClient(uri);
await client.connect();
const db = client.db("school");
const students = db.collection("students");
// Always close the connection when done
await client.close();Store your connection string in an environment variable (e.g. MONGODB_URI) — never hard-code credentials in source files.
Ready to test yourself?
Practice MongoDB— quiz & coding exercises