Connecting to Atlas in Code · MongoDB

Ch 1 · MongoDB Atlas and Cloud Deployment — card 2 of 4.

This script loads MongoClient from the mongodb package and connects to an Atlas cluster using the connection string copied from the Atlas dashboard. Notice the ping command sent to the admin database, a quick check that the connection works. It then inserts a test user and reads it back with findOne. Look at the try and finally blocks, which make sure the client closes even if something fails.

const { MongoClient } = require("mongodb");

// Connection string from Atlas dashboard
const uri = "mongodb+srv://<username>:<password>@<cluster-url>/?retryWrites=true&w=majority";

const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    await client.db("admin").command({ ping: 1 });
    console.log("Connected to Atlas!");
    
    const db = client.db("myapp");
    const col = db.collection("users");
    await col.insertOne({ name: "Test", createdAt: new Date() });
    const doc = await col.findOne({ name: "Test" });
    console.log("Document:", doc);
  } finally {
    await client.close();
  }
}
run();