MongoDB Drivers
mongosh is great for learning and administration, but applications talk to MongoDB through a driver: a library for your programming language. MongoDB maintains official drivers for C, C++, C#, Go, Java, Kotlin, Node.js, PHP, Python, Ruby, Rust, Scala and Swift. They all implement the same Query API, so everything in this course carries over, with each language's own syntax.
| Language | Package | Example call |
|---|---|---|
| Node.js | mongodb |
await products.find({ category: 'tea' }).toArray() |
| Python | pymongo |
list(products.find({"category": "tea"})) |
| Java | mongodb-driver-sync |
products.find(eq("category", "tea")) |
| C# | MongoDB.Driver |
products.Find(p => p.Category == "tea").ToList() |
| Go | go.mongodb.org/mongo-driver/v2 |
products.Find(ctx, bson.D{{"category", "tea"}}) |
This lesson uses the Node.js driver. The driver code needs a running MongoDB server and Node.js, so it is shown without a Run button; the mongosh examples next to it show the same operations on the sample data.
Installing and connecting
npm install mongodb// shop.mjs
import { MongoClient } from 'mongodb';
const uri = process.env.MONGODB_URI ?? 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db('shop');
const products = db.collection('products');
console.log(await products.countDocuments());
} finally {
await client.close();
}Create one MongoClient when your application starts and reuse it: it holds a connection pool and is safe to share across requests. Keep credentials out of the code (environment variables or a secrets manager).
CRUD with the driver
The methods look exactly like mongosh's, but they return Promises, so you await them:
const products = client.db('shop').collection('products');
// Create
const { insertedId } = await products.insertOne({ name: 'Kenya AA', category: 'coffee', price: 26, stock: 20 });
// Read
const teas = await products
.find({ category: 'tea' }, { projection: { name: 1, price: 1 } })
.sort({ price: 1 })
.toArray();
// Update
const res = await products.updateOne({ _id: insertedId }, { $inc: { stock: -1 } });
console.log(res.modifiedCount);
// Delete
await products.deleteMany({ stock: 0 });Note one difference: in the driver, the projection goes inside an options object ({ projection: { … } }), while mongosh accepts it directly as the second argument. The read above in mongosh:
print(db.products.find({ category: 'tea' }, { name: 1, price: 1 }).sort({ price: 1 }).toArray());[
{ _id: 8, name: 'Chamomile Calm', price: 8 },
{ _id: 7, name: 'Earl Grey', price: 9.5 },
{ _id: 9, name: 'Masala Chai', price: 11 },
{ _id: 6, name: 'Green Sencha', price: 12 }
]
Aggregation and cursors
const orders = client.db('shop').collection('orders');
const topCustomers = await orders.aggregate([
{ $match: { status: { $ne: 'cancelled' } } },
{ $group: { _id: '$customerId', spent: { $sum: '$total' } } },
{ $sort: { spent: -1 } },
{ $limit: 3 }
]).toArray();
// Large results: iterate instead of loading everything into memory
for await (const order of orders.find({ status: 'delivered' })) {
process(order);
}The same pipeline in mongosh:
print(db.orders.aggregate([
{ $match: { status: { $ne: 'cancelled' } } },
{ $group: { _id: '$customerId', spent: { $sum: '$total' } } },
{ $sort: { spent: -1 } },
{ $limit: 3 }
]).toArray());[
{ _id: 5, spent: 209 },
{ _id: 3, spent: 178 },
{ _id: 1, spent: 142.5 }
]
BSON types in the driver
The driver re-exports the BSON classes. ObjectIds from URL parameters must be converted from strings, and a common bug is querying by the string instead:
import { ObjectId, Decimal128 } from 'mongodb';
const id = new ObjectId(req.params.id); // throws on invalid input: validate it first
const doc = await products.findOne({ _id: id }); // { _id: req.params.id } would match nothing
await products.updateOne({ _id: id }, { $set: { price: Decimal128.fromString('19.99') } });The same type mismatch in mongosh:
db.items.insertOne({ _id: ObjectId('6650a1b2c3d4e5f601234567'), name: 'Kenya AA' });
print(db.items.findOne({ _id: '6650a1b2c3d4e5f601234567' }));
print(db.items.findOne({ _id: ObjectId('6650a1b2c3d4e5f601234567') }));null
{ _id: ObjectId('6650a1b2c3d4e5f601234567'), name: 'Kenya AA' }
Errors
Driver errors are MongoServerError objects with a numeric code, the same codes you saw in mongosh:
try {
await customers.insertOne({ email: 'ada@example.com' });
} catch (err) {
if (err.code === 11000) {
return res.status(409).json({ error: 'email already registered' });
}
throw err;
}Using the driver with TypeScript
The Node.js driver ships its own type definitions. Give a collection a document type and the compiler checks filters and updates:
interface Product { _id: number; name: string; category: string; price: number; stock: number; tags?: string[] }
const products = client.db('shop').collection<Product>('products');
const cheap = await products.find({ price: { $lt: 10 } }).toArray(); // Product[]
await products.updateOne({ _id: 7 }, { $inc: { stock: 5 } });
// await products.updateOne({ _id: 7 }, { $inc: { name: 1 } }); // compile error: name is not a numberTip: ODMs (object-document mappers) such as Mongoose (Node.js), MongoEngine / Beanie (Python) and Spring Data MongoDB (Java) add schemas, validation and model classes on top of the drivers.
Test yourself
How should a Node.js web server manage MongoClient?
- Create a new client for every request
- Create one client at startup and reuse it
- Use mongosh instead
- Open a client per collection
In the Node.js driver, how do you pass a projection to find()?
- As the second argument:
find(filter, { name: 1 }) - In the options:
find(filter, { projection: { name: 1 } }) - With
.project()only - Projections are not supported
Why does findOne({ _id: '6650a1b2c3d4e5f601234567' }) return null when the document exists?
- The id is too long
- The stored _id is an ObjectId, not a string
- findOne needs toArray()
- The driver is not connected