Documentation

MongoDB Shell (mongosh)

MongoDB Shell

Execute MongoDB commands and JavaScript scripts with syntax highlighting, intelligent autocomplete, and real-time error detection. View results in multiple formats and manage persistent shell sessions for your database operations.

Quick Start

Get started with MongoDB Shell in seconds:

  1. Open the MongoDB Shell activity from the sidebar
  2. Write your MongoDB command in the editor (e.g., db.customers.find({}))
  3. Press F5 to execute all scripts, or Ctrl+F5 to run selected text
  4. View results in the Shell Output or Result tabs below
MongoDB Shell interface showing editor on top with code, and result tabs below displaying query results in tree view

Interface Overview

Editor Panel

The top panel contains the code editor with full MongoDB JavaScript support:

  • Syntax Highlighting - Color-coded syntax for MongoDB shell commands and JavaScript
  • Auto-completion - Context-aware suggestions for collections, fields, and MongoDB methods
  • Error Detection - Real-time syntax validation and error highlighting
  • Line Numbers - Track execution progress and error locations
  • Minimap - Navigate large scripts quickly with the code minimap

Results Panel

The bottom panel displays execution results in tabbed interface:

  • Shell Output Tab - Shows print statements and execution logs
  • Result Tabs - Each query creates a new result tab (Result 1, Result 2, etc.)
  • View Modes - Switch between Tree View, Table View, and BSON View
  • Pagination Controls - Navigate through large result sets

Toolbar

Control buttons and status indicators:

  • Run Button - Execute all scripts in the editor
  • Shell Status - Shows connection status (ACTIVE, CONNECTING, UNKNOWN)
  • Save Script Dropdown - Save, load, export, and import scripts
  • Query History - Access previously executed commands
  • Keyboard Shortcuts - View all available shortcuts
  • Layout Toggle - Switch between horizontal and vertical split

Auto-completion

Press Ctrl+Space or start typing to get intelligent suggestions:

  • Database Commands - Type db. to see suggestions for getCollection(), createCollection(), etc.
  • Collection Names - db. shows all collections in the current database
  • Collection Methods - db.collection. shows find(), aggregate(), insertOne(), etc.
  • Field Names - Auto-complete field names based on collection schema
  • JavaScript Keywords - Standard JavaScript and MongoDB shell functions
Video SHEL02 Using Auto-completion - Learn how to use intelligent auto-completion to speed up your workflow. Type "db." to see all collection names, continue typing to see collection methods like find() and aggregate(), and watch how field names are suggested based on your collection schema. Press Ctrl+Space to trigger suggestions at any time.
Auto-complete dropdown showing collection names and methods after typing 'db.'

Execution Modes

The MongoDB Shell supports three execution modes for flexible script running:

Mode Shortcut Description
Run All F5 Execute all scripts in the editor from top to bottom. Scripts are automatically split and executed sequentially.
Run Selected Ctrl+F5 Execute only the currently selected text. Useful for testing specific commands or debugging portions of a script.
Run to Line Ctrl+Shift+F5 Execute all code from the beginning up to the current cursor line. Perfect for debugging and step-by-step execution.

Execution Behavior

When scripts are executed:

  • Script Splitting - Multiple commands are automatically detected and split for sequential execution
  • Line Highlighting - The currently executing line is highlighted in the editor
  • Progress Indicator - Shows "Running script X of Y" during execution
  • Error Handling - Execution stops on error, with the problematic line highlighted in red
  • Read-only Mode - Editor becomes read-only during execution to prevent conflicts
Video SHEL04 Writing and Executing Scripts - Watch how to write MongoDB scripts in the editor, then execute them using Run All (F5) to run the entire script or Run Selected (Ctrl+F5) to test specific portions. See how line highlighting shows execution progress, error handling catches issues, and the difference between running all scripts versus selected text for debugging.
Editor showing a highlighted line during script execution with progress indicator

Result Tabs

Query results are organized in tabs for easy navigation and comparison:

Shell Output Tab

The default tab that shows:

  • Print Statements - Output from print() or printjson()
  • Execution Logs - Success messages like "5 results" or "Document inserted"
  • Error Messages - Detailed error information with line numbers and suggestions
  • Script Progress - Status updates during multi-script execution

Actions available in Shell Output:

  • Clear Output - Remove all output messages
  • Copy All - Copy entire output to clipboard
  • Export - Save output to a text file

Result Tabs (Result 1, Result 2, etc.)

Each query that returns data creates a new result tab with:

  • Data Display - Documents rendered in Tree View, Table View, or BSON View
  • Pagination - Navigate through results with First, Previous, Next, Last buttons
  • View Options - Switch between different visualization modes
  • Close Button - Remove result tabs you no longer need
Multiple result tabs showing Shell Output and Result 1, Result 2 with tree view of documents
Video SHEL07 Viewing Results in Different Tabs - See how query results are organized in multiple tabs. Execute multiple queries and observe how each creates a new Result tab (Result 1, Result 2, etc.). Switch between Shell Output to see execution logs and Result tabs to view data. Explore the three view modes: Tree View for nested documents with expandable nodes, Table View for flat data comparison, and BSON View for raw JSON inspection.

View Modes

View Mode Best For Features
Tree View Complex nested documents Expandable/collapsible nodes, search, type indicators
Table View Flat documents, comparisons Sortable columns, resizable, multi-select rows
BSON View Raw data inspection JSON syntax highlighting, copy raw BSON

Pagination Controls

Navigate through large result sets efficiently:

  • Documents Displayed - Adjust the number of documents per page (default: 50)
  • First Page - Jump to the beginning of results
  • Previous Page - Go back one page
  • Next Page - Advance one page (only enabled when more results exist)
  • Last Page - Jump to the final page (calculates total count)

Script Management

Save and organize your MongoDB scripts for reuse and collaboration:

Save Script Dropdown

Click the Save Script dropdown in the toolbar to access:

  • New Script - Open a new shell activity with a blank script. Current script remains in its own tab.
  • Save - Save the current script. If not saved before, prompts for a name and location.
  • Save As - Save as a new script with a different name. Creates a copy of the current script.
  • Load - Open a previously saved script. Shows a dialog with all your saved shell scripts.
  • Export - Export script to JSON file for sharing or backup. Includes script content and metadata.
  • Export as JS - Export script as plain JavaScript file (.js) for use in other MongoDB tools or Node.js.
  • Import - Import a script from JSON file. Loads the script content into the current editor.
Save Script dropdown menu showing all options

Query History

Access and manage previously executed shell commands:

Opening Query History

Click the History button in the toolbar to open the Query History modal.

History Features

  • Automatic Recording - All executed scripts are automatically saved to history
  • Search - Filter history by script content or execution date
  • Preview - View script content before loading
  • Load to Editor - Click a history item to load it into the current editor
  • Execution Metadata - See when each script was executed and on which database
  • Filter by Type - History is filtered to show only shell scripts (not regular queries or SQL)
Query History modal showing list of previously executed shell scripts with dates and preview

Keyboard Shortcuts

Boost productivity with these keyboard shortcuts. Click the Keyboard Shortcuts button in the toolbar or press F1 to view the shortcuts modal.

Script Execution

Shortcut Action
F5 Run all scripts in the editor
Ctrl+F5 Run only the selected text
Ctrl+Shift+F5 Run all code up to the current cursor line

Editing

Shortcut Action
Ctrl+Space Trigger auto-complete suggestions
Ctrl+F Find text in script
Ctrl+H Find and replace
Ctrl+/ Comment/uncomment line
Shift+Alt+F Format script

Note: On macOS, use Cmd instead of Ctrl

Shell Session Management

MongoDB Shell maintains persistent sessions for each database connection:

Session Status

The shell status indicator shows:

  • ACTIVE - Shell session is connected and ready to execute commands
  • CONNECTING - Shell is initializing connection to the database
  • UNKNOWN - Connection status cannot be determined

Session Features

  • Persistent Variables - Variables defined in one execution persist for the session
  • Context Preservation - Database context (current db) is maintained
  • Multiple Sessions - Each shell activity has its own independent session
  • Auto-reconnect - Sessions automatically reconnect after network interruptions
  • Background Execution - Scripts continue running even if you switch to another tab

Creating a New Session

A new shell session is automatically created when you:

  • Open a MongoDB Shell activity for the first time
  • Click "New Script" in the Save Script dropdown
  • Click "Reconnect" if the session is closed

Closing a Session

Sessions are closed when you:

  • Close the shell activity tab
  • Disconnect from the database
  • Close the application

Pro Tips

  1. Use print() or printjson() to output debug information to the Shell Output tab while your script runs.
  2. Select a portion of your script and press Ctrl+F5 to test it in isolation without running the entire file.
  3. Use Ctrl+Space to trigger autocomplete suggestions for collections, fields, and MongoDB methods.
  4. Leverage the Query History to quickly re-run previous commands without retyping them.
  5. Save frequently used scripts to build a personal library of database operations and migrations.
  6. Use multi-cursor editing (Alt+Click) to make the same change in multiple places simultaneously.
  7. Toggle between horizontal and vertical layout to optimize screen space based on your script length and result complexity.
  8. Watch the execution time display to identify slow operations and optimize your queries accordingly.

Ready to try VisuaLeaf?

Download and start managing your MongoDB databases with ease.

Download Free Trial