MongoDB Shell JavaScript: Bulk Updates, Loops and Analysis

kyle_mongo2 pts0 comments

= 1024) leftSidebarOpen = false; if(window.innerWidth >= 1280) rightSidebarOpen = false"<br>:class="{ 'dark': $store.theme.dark, 'left-sidebar-closed': !leftSidebarDesktop, 'right-sidebar-closed': !rightSidebarDesktop, 'overflow-hidden': leftSidebarOpen || rightSidebarOpen, 'sidebars-closed': !leftSidebarDesktop && !rightSidebarDesktop }">

MongoDB Shell JavaScript: Bulk Updates, Loops & Analysis

Skip to content

Download Free

0" x-text="$store.bookmarks.count" class="nav-bookmarks-count" x-cloak>

Bookmarks

0">

No bookmarks yet.

Bookmarks are saved locally on this browser.

= 1280 ? rightSidebarDesktop = !rightSidebarDesktop : rightSidebarOpen = true"<br>class="nav-icon-btn"<br>:class="{ 'is-active': !(window.innerWidth >= 1280 ? rightSidebarDesktop : rightSidebarOpen) }"<br>aria-label="Toggle sidebar">

= 1280 ? !rightSidebarDesktop : !rightSidebarOpen" d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4V3z" fill="currentColor" stroke="none" />

VisuaLeaf

Download

Navigation

if (window.innerWidth

Search articles…

Preferences

Layout

Save Sidebar view

Remember if sidebars are open or closed across pages.

Save Sidebar layout preference

Enable Bookmarks

Save your favourite articles locally in this browser.

Enable Local Bookmarks

let scroll = window.scrollY;<br>let docHeight = document.documentElement.scrollHeight - window.innerHeight;<br>this.progress = docHeight > 0 ? Math.max(0, Math.min(1, scroll / docHeight)) : 0;<br>this.ticking = false;<br>});<br>}"<br>@scroll.window.passive="update()"<br>@resize.window.passive="update()"<br>x-init="update()"<br>class="fixed top-0 left-0 w-full h-[3px] z-[100] pointer-events-none">

MongoDB Shell scripting (mongosh) for bulk updates, loops, and MongoDB data analysis

Most mongosh tutorials focus on individual commands: find a document, update a field, or run an aggregation.<br>That is useful when you already know exactly what needs to change. Real cleanup work is often more complicated. You may need to analyze several collections, calculate a value, loop through the results, preview the affected documents, and only then run the updates.<br>I tested this with a small SaaS database called saas_platform. Some workspaces had more active users than their subscription allowed. The goal was to:<br>Find the workspaces above their seat limits<br>Select users who had been inactive for more than 90 days<br>Avoid deactivating owners and administrators<br>Preview every selected user<br>Deactivate the users in bulk<br>Revoke their active sessions<br>Verify that each workspace was back within its limit<br>This cannot be handled safely with one global updateMany() command. Each workspace has a different seat limit and needs to release a different number of seats.<br>That is where mongosh scripting becomes useful.<br>The database used for this test<br>The saas_platform database contains four collections:

Collection<br>What it contains

workspaces<br>Workspace plans and seat limits

users<br>User accounts and their activity

sessions<br>Login sessions

activityLogs<br>Login and administrative events

A workspace stores its subscription limit:<br>workspaceId: "WS-1001",<br>name: "Northstar Metrics",<br>plan: "Team",<br>seatLimit: 8,<br>status: "active"<br>The users reference that workspace through workspaceId:<br>userId: "USR-0009",<br>workspaceId: "WS-1001",<br>fullName: "Selene Mercer",<br>role: "viewer",<br>status: "active",<br>lastLoginAt: ISODate("2026-03-04T09:00:00Z")<br>The test database contains six workspaces and 56 users. Three workspaces are above their seat limits, with eight extra users in total.<br>Those eight users have not logged in for more than 90 days, but their accounts and sessions are still active.<br>The saas_platform database in VisuaLeaf, with its four collections and a workspace document open for inspection.Download the complete self-contained demo script. It creates a dedicated sample database and reproduces the same result shown in this article: eight users deactivated, eight active sessions revoked, and zero active sessions remaining. The script resets only the saas_platform database.<br>mongo_shell_scripting_demo

mongo_shell_scripting_demo.js<br>10 KB

download-circle

Mongosh can run JavaScript logic<br>Mongosh is not limited to isolated MongoDB commands. It provides a JavaScript and Node.js environment so you can use variables, arrays, functions, conditions, loops, and date calculations alongside your database operations.<br>The analysis, cleanup plan, and bulk-update blocks below form one connected script. Copy them into the same editor in the order shown and execute them together. Running the blocks as separate executions may cause variables such as cleanupPlan to be unavailable. The verification, index, explain(), and BSON Date checks are self-contained and can be executed separately.<br>For this workflow, I first selected the database and calculated the inactivity cutoff:<br>const appDb = db.getSiblingDB("saas_platform");

const inactiveDays = 90;<br>const referenceDate = new Date("2026-08-05T09:00:00Z");

const cutoffDate = new Date(<br>referenceDate.getTime() -<br>inactiveDays * 24 * 60 * 60 *...

database users active window bookmarks rightsidebardesktop

Related Articles