Skip to content

MongoDB Fundamentals

MongoDB Node.js Driver

The native driver: MongoClient, database, collection, and the smallest real query.

BeginnerAbout 5 minutes

The MongoDB Node.js driver is the library your backend uses to talk to the server. The shell is a client. Compass is a client. mongodb on npm is the client you ship. Mongoose sits on top of this driver — that is a later module. Start with the native API so you know what the ODM is wrapping.

  1. 01Node.js route / script
  2. 02mongodb driver (MongoClient)
  3. 03Database — app
  4. 04Collection — users
  5. 05findOne / find / insertOne …
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGO_URI);

await client.connect();

const db = client.db("app");
const users = db.collection("users");

const user = await users.findOne({
  email: "rahul@example.com",
});
MongoClient → database → collection → query
{
  _id: ObjectId("64a1b2c3d4e5f6a7b8c90001"),
  name: "Rahul",
  email: "rahul@example.com",
  city: "Bangalore",
  ...
}
findOne returns a document or null — not a cursor
  • MongoClient — the process-wide client. Holds the connection pool (next lesson).
  • client.db("app") — the database. Same idea as use app in the shell.
  • db.collection("users") — the collection. Same as db.users.
  • findOne — one document or null. find returns a cursor; call toArray() when you want an array.

Shell: db.users.findOne({ city: "Bangalore" }). Driver: users.findOne({ city: "Bangalore" }). Same filter document. CRUD from Node.js later is this API for insert, update and delete.

Interview question

How does a Node.js app talk to MongoDB?

Think about it first.