The $listSessions stage lists logical sessions across a sharded cluster when run on mongos—giving DBAs a single cluster-wide inventory instead of checking each shard individually with $listLocalSessions.
01
Cluster-wide
All shards.
02
mongos only
Run context.
03
admin DB
Pipeline host.
04
allUsers
Full visibility.
05
lastUse
Filter activity.
06
vs local
Scope compare.
Fundamentals
Definition and Usage
$listSessions is an aggregation stage that returns session documents for the entire sharded cluster. MongoDB tracks logical sessions (lsid) for retryable writes, transactions, and causal consistency—this stage exposes that cluster-level catalog to administrators.
💡
Beginner tip
On a sharded cluster, connect to mongos (not a shard mongod) and run on admin. For a single-node or replica-set check, use $listLocalSessions instead—it works on any mongod you connect to.
Use $listSessions during cluster health audits, connection-pool investigations, and transaction troubleshooting. Chain $match and $group afterward to summarize sessions by application user or recency.
Foundation
📝 Syntax
$listSessions accepts an optional options document:
mongosh
{
$listSessions: {
allUsers: <boolean>
}
}
Syntax Rules
First stage — $listSessions must be stage 1 in the pipeline.
mongos + admin — run via db.getSiblingDB("admin").aggregate([…]) on a mongos connection.
Sharded clusters — designed for cluster-wide session listing; not a substitute for per-shard local checks.
UUID of the logical session—matches lsid in $currentOp and driver logs.
id: UUID("f47ac10b-...")
userOutput
Owner of the session: user name and authentication db.
user: {
user: "reportingApp",
db: "admin"
}
lastUseOutput
ISODate when the session was last used—ideal for $match filters finding stale vs active sessions.
lastUse: ISODate("2026-07-07T...")
Hands-On
Examples Gallery
Sharded-cluster admin pipelines—connect via mongos, list sessions cluster-wide, monitor all users, summarize by application account, and compare with local and operation-level tools.
📚 Getting Started
Connect to mongos and run on admin.
Example 1 — Prerequisites (mongos + admin)
mongosh
// mongosh connection string must target mongos, e.g.:
// mongosh "mongodb://mongos-host:27017"
const admin = db.getSiblingDB("admin")
admin.aggregate([
{ $listSessions: {} }
])
/* Sample document shape:
{
id: UUID("..."),
lastUse: ISODate("2026-07-07T16:00:00Z"),
user: { user: "appService", db: "admin" },
txnNumber: Long("0")
}
*/
// Standalone / replica set without mongos?
// → use $listLocalSessions on each mongod instead
How It Works
$listSessions is a cluster-level admin stage. It does not read from your application collections—it reports server-managed session metadata visible only when connected through the sharded cluster router.
Example 2 — List your sessions (default)
mongosh
db.getSiblingDB("admin").aggregate([
{ $listSessions: {} },
{
$project: {
sessionId: "$id",
username: "$user.user",
authDb: "$user.db",
lastUse: 1,
txnNumber: 1,
_id: 0
}
},
{ $sort: { lastUse: -1 } }
])
// allUsers defaults to false
// → sessions owned by the user running this command
📤 Default scope:
Your mongosh session listed
Cluster-wide but filtered to your user
Safe for developers without listSessions on all users
How It Works
Even though the stage is cluster-wide, default visibility is limited to your own sessions—same privacy model as $listLocalSessions and $currentOp.
📈 Practical Patterns
Admin audits, summaries, and cross-tool comparison.
All app + admin sessions cluster-wide
Sorted by most recent lastUse
$limit caps large result sets
How It Works
DBAs use this during incidents—identifying which service accounts hold the most sessions or spotting accounts with unexpectedly high session counts after a deployment.
One row per user + auth db
activeSessions = count in last 30 min
latestActivity = most recent lastUse
How It Works
Chain standard aggregation stages after $listSessions—the session list becomes input for the same $match, $group, and $sort patterns you use on application data.
Example 5 — $listSessions vs $listLocalSessions vs $currentOp
$listSessions → mongos, cluster-wide
$listLocalSessions → per mongod
$currentOp → operations + lsid link
How It Works
Start with $listSessions for a cluster overview. Drill into a specific shard with $listLocalSessions. Use $currentOp when you need to correlate a session UUID with a running or idle operation.
Compare
📋 $listSessions vs related admin stages
Stage
Scope
Run on
Best for
$listSessions
Entire sharded cluster
mongos + admin
Cluster session audit
$listLocalSessions
Connected node only
mongod/mongos + admin
Per-shard or single-node check
$currentOp
Active/idle operations
admin
Slow queries, blocking ops
$limit
Caps pipeline rows
Any database
Trim large session result sets
$lookup
Join collections
App databases
Data queries—not session admin
🧠 How $listSessions Works
1
Clients connect via mongos
Application drivers open logical sessions routed through the sharded cluster query router.
Connect
2
Cluster catalog aggregated
mongos collects session records from across the deployment when $listSessions runs.
Aggregate
3
Documents emitted
One output document per session—filtered by allUsers unless admin privilege expands visibility.
List
=
🔒
Cluster session report
Downstream $group and $limit shape the data for ops dashboards or incident triage.
Important
📝 Notes
Run on mongos for sharded clusters—connecting directly to a shard mongod requires $listLocalSessions instead.
$listSessions must be the first pipeline stage on the admin database.
allUsers: true requires the listSessions privilege when authentication is enabled.
Session counts change continuously—sessions expire after inactivity per logicalSessionRefreshMillis.
Use $limit after listing when result sets are large.
$listSessions is the cluster-wide session inventory for sharded MongoDB: connect to mongos, run on admin, set allUsers when you need full visibility, and summarize with standard downstream stages.
For single-node checks, use $listLocalSessions. Next: $lookup for joining collections in application pipelines.
Connect through mongos for accurate cluster-wide session data
Use allUsers: true only with admin credentials during audits
Filter by lastUse to focus on recently active sessions
Add $limit when exploring large session lists interactively
Cross-check suspicious sessions with $currentOp and application logs
❌ Don’t
Run $listSessions on application databases like orders
Expect it on standalone deployments where $listLocalSessions is the right tool
Place stages before $listSessions in the pipeline
Grant listSessions to application service accounts unnecessarily
Confuse session inventory with live query monitoring—that is $currentOp
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $listSessions
Use these points whenever you audit sessions on a sharded cluster.
5
Core concepts
🌐01
Cluster-wide
All shards.
Scope
🚀02
mongos
Connect here.
Setup
👥03
allUsers
Full audit.
Access
⏰04
lastUse
Filter time.
Match
🔀05
vs local
Per-node alt.
Compare
❓ Frequently Asked Questions
$listSessions returns documents describing logical sessions tracked across the sharded cluster. Each document includes session metadata such as id, user, and lastUse. It provides a cluster-wide session view—broader than $listLocalSessions on a single mongod.
Connect to mongos and run on the admin database: db.getSiblingDB("admin").aggregate([{ $listSessions: {} }]). $listSessions must be the first pipeline stage. It is intended for sharded deployments, not standalone mongod diagnostics.
$listLocalSessions lists sessions on the connected mongod/mongos instance only. $listSessions (on mongos) aggregates session records across the sharded cluster. Use local for one-node checks; use listSessions for cluster-wide audits.
Default false shows only your sessions. allUsers: true lists every session in the cluster scope—requires listSessions privilege when access control is enabled.
Yes. Chain $match, $sort, $group, $project, and $limit after $listSessions—e.g. filter by lastUse, count sessions per application user, or limit to the 20 most recently used sessions.
$listSessions inventories session records cluster-wide. $currentOp shows live and idle operations with lsid fields. Use listSessions for session counts and staleness; use currentOp to see what operations are running now.
Did you know?
Logical sessions were introduced alongside retryable writes in MongoDB 3.6 and underpin multi-document transactions in 4.0+. The $listSessions stage is available on mongos for sharded clusters—whereas $listLocalSessions works on any individual mongod. See the official $listSessions docs.