MongoDB $listSessions Stage

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $listSessions?

$listSessions is a MongoDB aggregation stage that lists logical sessions across a sharded cluster when run on mongos—a single cluster-wide inventory instead of checking each shard with $listLocalSessions.

Remember
$listSessions = "who has sessions across the CLUSTER?"

db.getSiblingDB("admin").aggregate([
  { $listSessions: {} }
])

connect via mongos (sharded cluster)
must run on admin
must be the FIRST stage
allUsers: false → your sessions only (default)
allUsers: true  → every session in cluster scope
lastUse → when the session was last active

$this node only → $listLocalSessions
cluster view → $listSessions
UsePrefer
Cluster-wide session view (mongos)$listSessions
Sessions on this mongod/mongos only$listLocalSessions
Live operations / idle ops$currentOp

How to Use $listSessions in MongoDB

Connect to mongos, run on admin, put the stage first, then filter or project.

  1. Connect to mongos (sharded cluster router).
  2. Switch to admin: db.getSiblingDB("admin").
  3. Start with { $listSessions: {} } or { allUsers: true }.
  4. Optional: $match on lastUse, $sort, $limit.
  5. Optional: $project to keep id, user, and lastUse.
Option / fieldRole
allUsersfalse = yours; true = everyone in cluster scope
idLogical session identifier
userAuthenticated user (user + db)
lastUseLast activity timestamp

Pseudocode

Pseudocode
assert: connected to mongos (sharded cluster)
assert: pipeline runs on admin
assert: $listSessions is stage 1

sessions = logical sessions visible cluster-wide

if allUsers is false:
  keep only sessions for current user
else:
  keep all sessions in cluster scope
  (requires privilege when auth is on)

for each session:
  emit { id, user, lastUse, … }

// later $match / $sort / $project reshape the list

Cheat Sheet

Keep these facts handy during cluster session audits.

TopicDetail
TypeAggregation stage (admin diagnostics)
TargetPrefer mongos on a sharded cluster
DatabaseMust run on admin
PositionMust be first
Default scopeCaller’s sessions only
Admin scopeallUsers: true
PrivilegeOften listSessions for all users
vs $listLocalSessionsCluster-oriented vs this node only

Live Preview

Filter a sample cluster session snapshot (teaching model—not a live mongos connection).

Sample assumes you are logged in as appUser on mongos. Timestamps are relative to “now.”

Result
appUser @ admin     lastUse: 2 min ago
appUser @ admin     lastUse: 40 min ago

Worked Walkthrough — List Your Cluster Sessions

You are connected to mongos with mongosh. Goal: see your logical sessions across the cluster, newest activity first.

Calculation
1. Connect to mongos
2. db.getSiblingDB("admin")
3. $listSessions {}          ← first stage
4. Defaults: allUsers false  → only your sessions
5. $project id, user, lastUse
6. Optional: $sort { lastUse: -1 }

Any find()/update you run updates lastUse
on your client session record.

MongoDB Examples

These pipelines run on the admin database via mongos and inspect live session metadata (not a seeded collection). Results depend on who is connected to your cluster.

Example 1 — Setup / Prerequisites

Goal: connect to mongos, touch your client session, then list logical sessions cluster-wide. $listSessions reads server session metadata on admin—not documents from a collection you seed.

mongosh
// Touch a session (any database is fine)
db.getSiblingDB("test").products.findOne()

// List sessions — must use admin on mongos
db.getSiblingDB("admin").aggregate([
  { $listSessions: {} }
])

How It Works

  1. Session exists. Any command (here findOne) ties work to your logical session.
  2. Admin only. Switch with getSiblingDB("admin") before aggregating.
  3. Stage 1. $listSessions must be first; default allUsers: false shows your sessions.
  4. Output shape. Each result is session info (id, user, lastUse), not business data.

Example 2 — Clean Fields

Goal: after Example 1, keep only the fields you need for a quick audit of your cluster sessions.

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

How It Works

  1. List first. Stage 1 still emits full session documents.
  2. Project. Rename/keep id, user, and lastUse only.
  3. Sort recent first. Newest activity rises to the top.
  4. Default safety. Without allUsers, you only see your own sessions.

Example 3 — allUsers + Recent

Goal: after Example 1, admin view of every session in cluster scope, then keep only those active in the last hour and summarize per user.

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

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

// allUsers: true needs listSessions privilege when auth is enabled
// Prefer mongos — cluster-oriented view vs $listLocalSessions

How It Works

  1. Widen scope. allUsers: true includes every session in cluster scope.
  2. Filter after. $match on lastUse keeps recent activity.
  3. Summarize. $group counts sessions per application user.
  4. Cluster tip. For one-node checks, use $listLocalSessions instead.

Edge Cases & Pitfalls

Check these before using $listSessions in production audits.

mongos

Prefer mongos on a sharded cluster

For cluster-wide inventory, connect through the router. For a single mongod, use $listLocalSessions.

admin

Must run on the admin database

Starting on an app database fails. Always use db.getSiblingDB("admin").

order

Must be the first stage

Put $match / $project after it. Nothing may precede $listSessions.

priv

allUsers needs privilege

With access control, allUsers: true typically requires the listSessions privilege.

Performance Notes

ApproachCostBest for
Default $listSessionsLight metadata readYour own sessions
allUsers: true + $matchLarger list, then filterCluster admin audits
Polling every secondExtra admin loadAvoid unless needed

Prefer narrow projections and time filters so dashboards stay small. Pair with $currentOp when you also need running operations.

Key Takeaways

  • Role: list logical sessions across the sharded cluster (mongos).
  • Rules: run on admin; stage must be first.
  • Scope: default = you; allUsers: true = everyone in cluster scope.
  • Local: use $listLocalSessions for one-node views.

One line: $listSessions answers “which logical sessions exist across this sharded cluster right now?”

Frequently Asked Questions

$listSessions returns documents describing logical sessions tracked across a sharded cluster when you run it on mongos. Each document includes session metadata such as id, user, and lastUse—broader than $listLocalSessions on a single node.
Connect to mongos and run on admin: db.getSiblingDB("admin").aggregate([{ $listSessions: {} }]). The stage must be first. Prefer $listLocalSessions for single-node or replica-set checks.
By default (allUsers: false), you see only sessions for the user running the command. Set allUsers: true to list every session in cluster scope—requires listSessions privilege when access control is enabled.
$listLocalSessions lists sessions on the connected mongod/mongos only. $listSessions on mongos aggregates session records across the sharded cluster. Use local for one-node diagnostics; use listSessions for cluster-wide audits.
Yes. $listSessions must be stage 1, but you can chain $match, $sort, $project, $group, and $limit afterward—for example filter by lastUse or count sessions per user.
$listSessions inventories session records. $currentOp shows live and idle operations (often with lsid). Use listSessions for session counts and staleness; use currentOp to see what is running now.

Next: $lookup

Join related documents from another collection inside the aggregation pipeline.

$lookup tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful