MongoDB $listLocalSessions Stage

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
Admin

What You’ll Learn

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.

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.

📝 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.
mongosh
db.getSiblingDB("admin").aggregate([
  { $listLocalSessions: {} }
])

⚡ Quick Reference

QuestionAnswer
ScopeSessions on the connected mongod/mongos only
Databaseadmin
Stage positionMust be first
Default visibilityYour sessions only (allUsers: false)
Common output fieldsid, user, lastUse, txnNumber
Cluster-wide alternative$listSessions on mongos
Your sessions
{ $listLocalSessions: {} }

Default

All users
{ $listLocalSessions: {
  allUsers: true
}}

Admin view

Recent only
{ $match: {
  lastUse: { $gte: cutoff }
}}

After stage

Clean fields
{ $project: {
  id: 1, user: 1,
  lastUse: 1
}}

Trim output

🧰 Parameters & Output Fields

Stage option and common fields in each returned session document:

allUsers Optional

When true, return sessions for all authenticated users on this node. Requires listSessions privilege with auth enabled.

allUsers: false  // default
allUsers: true   // admin
id Output

UUID identifying the logical session—matches lsid seen in operation logs and $currentOp output.

id: UUID("a1b2c3d4-...")
user Output

User document (user name and db auth source) that owns the session.

user: {
  user: "appUser",
  db: "admin"
}
lastUse Output

ISODate of the last operation that touched this session—filter with $match to find stale or active sessions.

lastUse: ISODate("2026-07-07T...")

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

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

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.

Example 4 — Sessions active in the last hour

mongosh
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000)

db.getSiblingDB("admin").aggregate([
  { $listLocalSessions: { allUsers: true } },
  { $match: { lastUse: { $gte: oneHourAgo } } },
  {
    $group: {
      _id: { user: "$user.user", db: "$user.db" },
      sessionCount: { $sum: 1 },
      latestActivity: { $max: "$lastUse" }
    }
  },
  { $sort: { sessionCount: -1 } }
])

// $match after $listLocalSessions is valid
// $group summarizes sessions per application user

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

mongosh
// LOCAL — this mongod only
db.getSiblingDB("admin").aggregate([
  { $listLocalSessions: { allUsers: true } },
  { $count: "localSessionCount" }
])

// CLUSTER — mongos only (sharded deployments)
// db.getSiblingDB("admin").aggregate([
//   { $listSessions: { allUsers: true } },
//   { $count: "clusterSessionCount" }
// ])

// OPERATIONS — active/idle ops tied to sessions
db.getSiblingDB("admin").aggregate([
  { $currentOp: { allUsers: true, idleSessions: true } },
  { $match: { lsid: { $exists: true } } },
  {
    $project: {
      op: 1,
      active: 1,
      secs_running: 1,
      lsid: 1,
      _id: 0
    }
  },
  { $limit: 10 }
])

// $listLocalSessions → session records
// $currentOp         → what those sessions are doing now

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.

🧠 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.

📝 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.
  • Previous topic: $limit. Next: $listSessions.

Conclusion

$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.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about $listLocalSessions

Use these points whenever you audit sessions on a MongoDB node.

5
Core concepts
📚 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.

Continue the Stages Series

Inspect local sessions with $listLocalSessions, then go cluster-wide with $listSessions.

Next: $listSessions →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful