MongoDB $listLocalSessions Stage

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

What Is $listLocalSessions?

$listLocalSessions is a MongoDB aggregation stage that lists logical sessions on the current mongod (or mongos)—server-side records used for retryable writes, transactions, and causal consistency.

Remember
$listLocalSessions = "who has sessions on THIS node?"

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

must run on admin
must be the FIRST stage
allUsers: false → your sessions only (default)
allUsers: true  → every session on this node
lastUse → when the session was last active

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

How to Use $listLocalSessions in MongoDB

Run on admin, put the stage first, then filter or project.

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

Pseudocode

Pseudocode
assert: pipeline runs on admin
assert: $listLocalSessions is stage 1

sessions = logical sessions cached on THIS node

if allUsers is false:
  keep only sessions for current user
else:
  keep all sessions on this node
  (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 session audits.

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

Live Preview

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

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

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

Worked Walkthrough — List Your Sessions

You are connected with mongosh. Goal: see your logical sessions on this node, newest activity first.

Calculation
1. db.getSiblingDB("admin")
2. $listLocalSessions {}     ← first stage
3. Defaults: allUsers false  → only your sessions
4. $project id, user, lastUse
5. 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 and inspect live session metadata (not a seeded collection). Results depend on who is connected to your server.

Example 1 — Setup / Prerequisites

Goal: touch your client session, then list logical sessions on this node. $listLocalSessions 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
db.getSiblingDB("admin").aggregate([
  { $listLocalSessions: {} }
])

How It Works

  1. Session exists. Any command (here findOne) updates your session’s lastUse.
  2. Admin only. Switch with getSiblingDB("admin") before aggregating.
  3. Stage 1. $listLocalSessions must be first; default scope is your sessions only.
  4. This node. Results are local to the mongod/mongos you are connected to—not cluster-wide.

Example 2 — Clean Fields

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

mongosh
db.getSiblingDB("admin").aggregate([
  { $listLocalSessions: {} },
  {
    $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 on this node, 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([
  { $listLocalSessions: { 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
// Still THIS node only — check each replica set member separately

How It Works

  1. Widen scope. allUsers: true includes every session on this node.
  2. Filter after. $match on lastUse keeps recent activity.
  3. Summarize. $group counts sessions per application user.
  4. Replica tip. Primaries and secondaries each have their own local table.

Edge Cases & Pitfalls

Check these before using $listLocalSessions in production audits.

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

scope

This node only

Replica set members do not share one local session list. Audit the node that serves your traffic. For cluster-wide views, use $listSessions.

priv

allUsers needs privilege

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

Performance Notes

ApproachCostBest for
Default $listLocalSessionsLight metadata readYour own sessions
allUsers: true + $matchLarger list, then filterAdmin 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 on this MongoDB node.
  • Rules: run on admin; stage must be first.
  • Scope: default = you; allUsers: true = everyone here.
  • Cluster: use $listSessions for wider views.

One line: $listLocalSessions answers “which logical sessions exist on this server right now?”

Frequently Asked Questions

$listLocalSessions returns documents describing logical sessions recorded on the current mongod (or mongos) you are connected to—not cluster-wide. Each document includes session metadata such as id, user, and lastUse.
Run on admin: db.getSiblingDB("admin").aggregate([{ $listLocalSessions: {} }]). The stage must be first. It does not run on regular application collections.
By default (allUsers: false), you see only sessions for the user running the command. Set allUsers: true to list every session on this node—requires listSessions privilege when access control is enabled.
$listLocalSessions is scoped to the connected mongod/mongos only. $listSessions (typically on mongos) can return session information across a sharded cluster. Use local for one-node diagnostics.
Yes. $listLocalSessions must be stage 1, but you can chain $match, $sort, $project, and $limit afterward—for example filter by lastUse or project only id and user.
$currentOp shows operations (including idle sessions). $listLocalSessions focuses on logical session records themselves. Use both when debugging transactions or connection-pool session load.

Next: $listSessions

List sessions with a wider (often cluster-oriented) view than the local stage.

$listSessions tutorial →

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