SyntaxStudy
Sign Up
MongoDB Installing and Connecting to MongoDB
MongoDB Beginner 1 min read

Installing and Connecting to MongoDB

MongoDB can be run locally by installing MongoDB Community Edition or accessed as a fully managed service through MongoDB Atlas. Local installation is straightforward on all major operating systems and includes the mongod server process and the mongosh shell. The MongoDB Node.js driver and the Mongoose ODM are the two most common ways to connect from a JavaScript application. The connection string format is mongodb://username:password@host:port/database for standalone servers and mongodb+srv://... for Atlas clusters, which handles DNS-based replica set discovery automatically. Environment variables should always be used to store connection strings so credentials are never hard-coded in source files.
Example
// Install MongoDB Node.js driver
npm install mongodb

// Connect with the native driver (Node.js)
const { MongoClient } = require('mongodb');

const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function main() {
  await client.connect();
  console.log('Connected to MongoDB');

  const db = client.db('myAppDB');
  const users = db.collection('users');

  // Quick ping to verify connection
  await db.command({ ping: 1 });
  console.log('Ping successful');

  // Always close the connection when done
  await client.close();
}

main().catch(console.error);

// .env file (never commit this)
// MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/myAppDB