MongoDB $listSessions Stage

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

What You’ll Learn

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.

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.

📝 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.
  • allUsers — optional; default false. true requires listSessions privilege with auth enabled.
  • Empty object OK{ $listSessions: {} } uses defaults.
  • Not in $facet — cannot nest inside $facet sub-pipelines.
mongosh
// Connect to mongos, then:
db.getSiblingDB("admin").aggregate([
  { $listSessions: {} }
])

⚡ Quick Reference

QuestionAnswer
ScopeCluster-wide (sharded deployment via mongos)
Connect tomongos (not individual shard mongod)
Databaseadmin
Stage positionMust be first
Per-node alternative$listLocalSessions on each mongod
Common fieldsid, user, lastUse, txnNumber
Your sessions
{ $listSessions: {} }

Default

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

Cluster audit

Count total
{ $listSessions: {
  allUsers: true
}},
{ $count: "total" }

Quick metric

By user
{ $group: {
  _id: "$user.user",
  n: { $sum: 1 }
}}

Summary

🧰 Parameters & Output Fields

Stage option and typical fields in each session document:

allUsers Optional

When true, return sessions for all authenticated users cluster-wide. Requires listSessions privilege when access control is enabled.

allUsers: false  // default
allUsers: true   // DBA audit
id Output

UUID of the logical session—matches lsid in $currentOp and driver logs.

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

Owner of the session: user name and authentication db.

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

ISODate when the session was last used—ideal for $match filters finding stale vs active sessions.

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

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

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.

Example 3 — All cluster sessions (allUsers: true)

mongosh
db.getSiblingDB("admin").aggregate([
  { $listSessions: { allUsers: true } },
  { $sort: { lastUse: -1 } },
  {
    $project: {
      sessionId: "$id",
      username: "$user.user",
      authDb: "$user.db",
      lastUse: 1,
      _id: 0
    }
  },
  { $limit: 50 }
])

// Requires listSessions privilege (auth enabled)
// One query → sessions across entire sharded cluster

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.

Example 4 — Session count per application user

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

db.getSiblingDB("admin").aggregate([
  { $listSessions: { allUsers: true } },
  { $match: { lastUse: { $gte: thirtyMinAgo } } },
  {
    $group: {
      _id: { user: "$user.user", db: "$user.db" },
      activeSessions: { $sum: 1 },
      latestActivity: { $max: "$lastUse" }
    }
  },
  { $sort: { activeSessions: -1 } },
  {
    $project: {
      username: "$_id.user",
      authDb: "$_id.db",
      activeSessions: 1,
      latestActivity: 1,
      _id: 0
    }
  }
])

// Surfaces which apps hold the most recent sessions
// Useful after scaling events or connection-pool changes

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

mongosh
// CLUSTER-WIDE (mongos)
db.getSiblingDB("admin").aggregate([
  { $listSessions: { allUsers: true } },
  { $count: "clusterSessionCount" }
])

// SINGLE NODE (any mongod — e.g. one shard)
// db.getSiblingDB("admin").aggregate([
//   { $listLocalSessions: { allUsers: true } },
//   { $count: "localSessionCount" }
// ])

// LIVE OPS (mongos or mongod admin)
db.getSiblingDB("admin").aggregate([
  { $currentOp: { allUsers: true, idleSessions: true } },
  { $match: { lsid: { $exists: true } } },
  {
    $project: {
      op: 1,
      active: 1,
      secs_running: 1,
      lsid: 1,
      client: 1,
      _id: 0
    }
  },
  { $limit: 10 }
])

// Pick the narrowest tool:
// listSessions      → cluster session inventory
// listLocalSessions → one node's sessions
// currentOp         → what sessions are doing now

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.

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

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

Conclusion

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

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about $listSessions

Use these points whenever you audit sessions on a sharded cluster.

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

Continue the Stages Series

Audit cluster sessions with $listSessions, then join data with $lookup.

Next: $lookup →

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