MongoDB Fundamentals
MongoDB Node.js Driver
The native driver: MongoClient, database, collection, and the smallest real query.
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.
- 01Node.js route / script
- 02mongodb driver (MongoClient)
- 03Database — app
- 04Collection — users
- 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",
});{
_id: ObjectId("64a1b2c3d4e5f6a7b8c90001"),
name: "Rahul",
email: "rahul@example.com",
city: "Bangalore",
...
}- MongoClient — the process-wide client. Holds the connection pool (next lesson).
client.db("app")— the database. Same idea asuse appin the shell.db.collection("users")— the collection. Same asdb.users.findOne— one document ornull.findreturns a cursor; calltoArray()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?
Through the official driver. You construct a MongoClient, pick a database, pick a collection, then call findOne, find, insertOne and so on. The filter objects are the same shape as in mongosh. Mongoose is optional and sits on top of this.