Connecting from an application & the tooling
|
This section documents the current MongoDB 8.x server line as published at the MongoDB Server Manual, which is the reference these pages are written and verified against. No specific patch version is pinned. Some capabilities (Atlas Search, Atlas Vector Search, and parts of encryption and backup) are Atlas-only — they are linked, not documented in depth. This content was generated with the assistance of AI and should be verified against the official manual before being relied on in production, since MongoDB iterates quickly. This section’s bibliography lists the reference material consulted while preparing these pages. |
An application never speaks the wire protocol directly — it uses an official driver, configured by a connection-string URI, holding a pooled connection to the deployment. This page covers the drivers, the URI and its options, why the client is a singleton, the Stable API, and the surrounding command-line and GUI tooling.
Official drivers
MongoDB publishes and maintains drivers for Node.js, Python (PyMongo), Java, C#/.NET, Go, Rust, PHP, Ruby,
C++, Kotlin, and Scala. They differ in idiom — callbacks and promises, blocking and async, builders and
plain documents — but every one exposes the same operations you use in mongosh: insertOne/insertMany,
find, updateOne/updateMany, deleteOne/deleteMany, aggregate, bulkWrite, transactions, and
change streams. Learning the query and pipeline language once carries across all of them.
// Node.js driver
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);
const orders = client.db("shop").collection("orders");
await orders.insertOne({ customerId: 42, total: 19.99, status: "OPEN" });
const open = await orders
.find({ status: "OPEN" })
.sort({ orderDate: -1 })
.limit(20)
.toArray();
const byCustomer = await orders.aggregate([
{ $match: { status: "OPEN" } },
{ $group: { _id: "$customerId", total: { $sum: "$total" } } }
]).toArray();
The same three operations in PyMongo — identical query documents, identical pipeline:
from pymongo import MongoClient, DESCENDING
import os
client = MongoClient(os.environ["MONGODB_URI"])
orders = client["shop"]["orders"]
orders.insert_one({"customerId": 42, "total": 19.99, "status": "OPEN"})
open_orders = list(
orders.find({"status": "OPEN"}).sort("orderDate", DESCENDING).limit(20)
)
by_customer = list(orders.aggregate([
{"$match": {"status": "OPEN"}},
{"$group": {"_id": "$customerId", "total": {"$sum": "$total"}}},
]))
See MongoDB Drivers for the per-language guides, and CRUD: query for the query language the driver examples above reuse verbatim.
The connection string URI
Every driver is configured from one URI. The two schemes:
-
mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=rs0— an explicit seed list. You name every member; the driver discovers the rest of the topology from them. -
mongodb+srv://cluster.example.com/— DNS seedlist. A single hostname whose DNSSRVrecords supply the member list and whoseTXTrecord supplies default options. Atlas hands you this form; it means the member list can change without touching the app.
Common options, given as URI query parameters:
-
replicaSet=rs0— the replica-set name the driver must verify it is connected to. -
authSource=admin— the database that holds the user’s credentials (oftenadmin, not the app database). -
retryWrites=true— retry a write once, automatically, after a transient network error or a failover (the default in current drivers). -
w=majority— default write concern: acknowledge only after a majority of members have the write. -
readPreference=secondaryPreferred— where reads may be routed (primaryby default). -
tls=true— require TLS for the connection (implied bymongodb+srv://). -
maxPoolSize=100— upper bound on connections in the pool (see below).
const uri =
"mongodb+srv://appuser:pw@cluster.example.com/shop" +
"?authSource=admin&retryWrites=true&w=majority" +
"&readPreference=secondaryPreferred&maxPoolSize=50";
uri = (
"mongodb://appuser:pw@rs1:27017,rs2:27017,rs3:27017/shop"
"?replicaSet=rs0&authSource=admin&retryWrites=true&w=majority&tls=true"
)
See Connection String URI Format for every
option, and Replication for how the seed list and replicaSet name
drive topology discovery and failover.
Connection pooling and the singleton client
The driver’s client object owns a connection pool per server — a set of reusable sockets, capped at
maxPoolSize — plus background threads that monitor topology. Creating a client is therefore expensive:
DNS resolution, TCP and TLS handshakes, an initial hello to every member, and authentication.
Create one client for the lifetime of the process and share it across all requests. A new client per request (or per function invocation) exhausts server connections, adds handshake latency to every call, and defeats the pool. In serverless runtimes, cache the client outside the handler so it survives warm invocations.
// module scope -- created once, imported everywhere
export const client = new MongoClient(process.env.MONGODB_URI, { maxPoolSize: 50 });
await client.connect();
See Connection Pool Overview and your driver’s connection-management guide.
The Stable API
Declaring { apiVersion: "1" } on the client opts every operation into a versioned, backward-compatible
subset of the server API. The server then guarantees those commands behave identically across future
releases, so a server upgrade cannot silently change your app’s behaviour. Add strict: true to have the
server reject any command outside the versioned set, which surfaces accidental use of unstable features at
development time.
const client = new MongoClient(uri, {
serverApi: { version: "1", strict: true, deprecationErrors: true }
});
from pymongo.server_api import ServerApi
client = MongoClient(uri, server_api=ServerApi("1", strict=True, deprecation_errors=True))
See Stable API.
Tooling
mongosh — the interactive shell and a full JavaScript environment: it takes the same connection URI as a
driver, runs scripts with mongosh --file script.js or mongosh --eval '…', and loads ~/.mongoshrc.js on
startup for custom prompts, helpers, and default settings. It is the reference environment the CRUD and
aggregation pages are written against — see Getting started.
mongosh "mongodb+srv://cluster.example.com/shop" --username appuser
mongosh --file migrate-orders.js "mongodb://localhost:27017"
// ~/.mongoshrc.js
prompt = () => `${db.getName()}> `;
config.set("displayBatchSize", 20);
MongoDB Compass — the official GUI: browse and edit documents, build queries and aggregation pipelines
visually, and read a graphical explain plan to see index usage. Useful for exploring an unfamiliar data set
and for prototyping a pipeline before pasting it into code.
Compass documentation.
MongoDB Database Tools — the standalone bundle of mongodump, mongorestore, mongoexport,
mongoimport, bsondump, mongostat, mongotop, and mongofiles, versioned and installed separately from
the server. Database Tools. See
Backups, import/export & GridFS for how they are used.
Atlas CLI — atlas, the command-line interface to MongoDB Atlas: create and manage clusters, database
users, network access, and backups, and spin up a local Atlas deployment for development. It targets the
hosted platform, so it is linked rather than documented here:
Atlas CLI.