The $listLocalSessions stage lists logical sessions on the current mongod (or mongos)—the server-side records MongoDB uses for retryable writes, transactions, and causal consistency. Essential for admin troubleshooting and session audits.
01
Local scope
This node only.
02
admin DB
Run context.
03
allUsers
See all sessions.
04
lastUse
Activity time.
05
First stage
Pipeline rule.
06
vs $listSessions
Local vs cluster.
Fundamentals
Definition and Usage
$listLocalSessions is an aggregation stage that returns session documents tracked on the connected server instance. MongoDB assigns every client connection a logical session ID (lsid); this stage exposes those records for monitoring—not application data from your collections.
💡
Beginner tip
Sessions are not the same as user login accounts. A session is a server-side context for a client connection—used for transactions, retryable writes, and snapshot reads. Run $listLocalSessions on admin, not on your app database.
Use $listLocalSessions when investigating stuck transactions, connection leaks, or unexpected session counts on a single node. For cluster-wide session views on a sharded deployment, use $listSessions on mongos instead.
Foundation
📝 Syntax
$listLocalSessions accepts an optional options document:
mongosh
{
$listLocalSessions: {
allUsers: <boolean>
}
}
Syntax Rules
First stage — $listLocalSessions must be stage 1 in the pipeline.
admin database — run via db.getSiblingDB("admin").aggregate([…]).
allUsers — optional; default false (your sessions only). true lists all users’ sessions on this node.
Empty object OK — { $listLocalSessions: {} } uses defaults.
Post-filter — add $match, $sort, $project after the stage.
Not in $facet — cannot nest inside $facet sub-pipelines.
UUID identifying the logical session—matches lsid seen in operation logs and $currentOp output.
id: UUID("a1b2c3d4-...")
userOutput
User document (user name and db auth source) that owns the session.
user: {
user: "appUser",
db: "admin"
}
lastUseOutput
ISODate of the last operation that touched this session—filter with $match to find stale or active sessions.
lastUse: ISODate("2026-07-07T...")
Hands-On
Examples Gallery
Admin-database pipelines—list your sessions, monitor all users, filter by recency, build a summary report, and compare with related diagnostic stages.
📚 Getting Started
Connect to admin and understand session output.
Example 1 — Prerequisites and basic run
mongosh
// Connect with mongosh (sessions exist while clients are connected)
// Switch to admin — required for $listLocalSessions
const admin = db.getSiblingDB("admin")
admin.aggregate([
{ $listLocalSessions: {} }
])
/* Each document represents one logical session, e.g.:
{
id: UUID("..."),
lastUse: ISODate("2026-07-07T15:30:00Z"),
user: { user: "myApp", db: "admin" },
txnNumber: Long("0")
}
*/
// Generate a session: any query creates/updates your client session
db.products.findOne()
How It Works
Your mongosh connection already has a logical session. Running a query updates lastUse. Results vary by server state—unlike collection tutorials, you inspect live server metadata rather than seeded documents.
Example 2 — List your own sessions (default)
mongosh
db.getSiblingDB("admin").aggregate([
{ $listLocalSessions: {} },
{
$project: {
sessionId: "$id",
username: "$user.user",
authDb: "$user.db",
lastUse: 1,
txnNumber: 1,
_id: 0
}
}
])
// allUsers defaults to false
// → only sessions for the authenticated user running this command
📤 Default scope:
Your mongosh session appears
Other users' sessions hidden
Safe for non-admin developers
How It Works
Without allUsers, MongoDB filters to the caller’s sessions—similar to how $currentOp defaults to your operations unless allUsers: true is set.
📈 Practical Patterns
Admin monitoring, filtering, and cross-stage comparison.
Example 3 — All sessions on this node (allUsers: true)
mongosh
db.getSiblingDB("admin").aggregate([
{ $listLocalSessions: { allUsers: true } },
{ $sort: { lastUse: -1 } },
{
$project: {
sessionId: "$id",
username: "$user.user",
authDb: "$user.db",
lastUse: 1,
_id: 0
}
},
{ $limit: 20 }
])
// Requires listSessions privilege when auth is enabled
// Shows every recorded session on THIS mongod only
📤 Admin view:
All app + admin client sessions
Sorted by most recent lastUse
Replica set: run on each member separately
How It Works
DBAs use allUsers: true during incident response—spotting runaway connection pools or apps holding sessions open. On a replica set, each secondary and primary maintains its own local session table.
Only sessions with lastUse ≥ 1 hour ago
Grouped by user + auth db
sessionCount shows connection load
How It Works
Unlike stages that must stay first with no predecessors, $listLocalSessions only requires being stage 1—you freely chain analytics stages after it to build monitoring dashboards.
Example 5 — Compare with $listSessions and $currentOp
$listLocalSessions → this node's sessions
$listSessions → cluster-wide (mongos)
$currentOp → live operations + lsid
How It Works
Pick the narrowest tool: local session inventory for one node, cluster sessions for sharded overview, $currentOp when you need to see running queries and link them to a session ID.
Compare
📋 $listLocalSessions vs related admin stages
Stage
Scope
Best for
$listLocalSessions
Connected mongod/mongos only
Per-node session inventory
$listSessions
Cluster-wide (via mongos)
Sharded session overview
$currentOp
Active/idle operations
Slow queries, blocking ops, live lsid
$collStats
Collection storage metrics
Disk/index size—not sessions
$indexStats
Index usage counters
Query optimization—not sessions
🧠 How $listLocalSessions Works
1
Client connects
MongoDB assigns a logical session ID (lsid) to the client connection for retryable writes and transactions.
Connect
2
Session recorded locally
The mongod stores session metadata—user, lastUse, transaction counters—on that instance.
Track
3
Stage reads catalog
$listLocalSessions emits one document per session, optionally filtered by allUsers.
List
=
🔒
Session report
Downstream stages filter, sort, or aggregate session docs for ops dashboards.
Important
📝 Notes
Run on the admin database—never on application collections like orders or users.
$listLocalSessions must be the first pipeline stage.
allUsers: true needs the listSessions privilege when authentication is enabled.
Results reflect the connected node—repeat on each replica set member for full coverage.
Sessions expire after inactivity (logicalSessionRefreshMillis, default 5 minutes)—counts change over time.
$listLocalSessions gives you a per-node view of MongoDB logical sessions—run it on admin, use allUsers when you need full visibility, and chain $match / $group for summaries.
For sharded clusters, follow with $listSessions on mongos. Pair with $currentOp to see what those sessions are executing.
Run on admin with a user that has appropriate monitoring privileges
Use allUsers: true only when investigating production issues
Filter by lastUse to focus on recently active sessions
Combine with $currentOp to correlate sessions with running operations
Check each replica set member separately for complete local coverage
❌ Don’t
Run $listLocalSessions on application databases
Place other stages before $listLocalSessions in the pipeline
Assume local results represent the entire sharded cluster
Grant listSessions broadly to non-admin application users
Expect $listLocalSessions inside $facet to work
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $listLocalSessions
Use these points whenever you audit sessions on a MongoDB node.
5
Core concepts
🔒01
Local only
This node.
Scope
📚02
admin DB
Run context.
Setup
👥03
allUsers
Admin option.
Access
⏰04
lastUse
Activity time.
Filter
🔀05
vs $listSessions
Local vs cluster.
Compare
❓ Frequently Asked Questions
$listLocalSessions returns documents describing logical sessions recorded on the current mongod (or mongos) instance you are connected to—not cluster-wide. Each document includes session metadata such as id, user, and lastUse timestamp.
Run the pipeline on the admin database: db.getSiblingDB("admin").aggregate([{ $listLocalSessions: {} }]). The stage must be first in the pipeline. It does not run on regular application collections.
By default (allUsers: false), you see only sessions owned by the user running the command. Set allUsers: true to list every session on this node—requires listSessions privilege when access control is enabled.
$listLocalSessions scopes to the connected mongod/mongos only. $listSessions (on mongos) can return session information across the sharded cluster. Use local for one-node diagnostics; use listSessions for cluster-wide session views.
Yes. $listLocalSessions must be stage 1, but you can chain $match, $sort, $project, and $limit afterward—e.g. filter by lastUse to find recently active sessions or project only id and user fields.
$currentOp shows active and idle operations (including idleSessions). $listLocalSessions focuses on logical session records themselves. Use both when debugging transaction timeouts, orphaned sessions, or connection pool issues.
Did you know?
Logical sessions power retryable writes and multi-document transactions in MongoDB 4.0+. Sessions expire after logicalSessionRefreshMillis (default 300000 ms = 5 minutes) without activity—the server reaps stale session records automatically. See the official $listLocalSessions docs.