MongoDB Shell (mongosh)

2.8.2 · active · verified Wed Apr 22

mongosh is the official command-line interface (CLI) for interacting with MongoDB deployments. It provides a modern JavaScript-based REPL (Read-Eval-Print Loop) for database administration, data manipulation, and development. The npm package `mongosh` acts as a convenience wrapper, primarily distributing the compiled `mongosh` binary rather than a JavaScript library for programmatic import. The current stable version is 2.8.2. New versions are released frequently, often coinciding with MongoDB server updates, Node.js runtime upgrades (e.g., moving to Node.js 24 in v2.7.0), and regular bug fixes and minor feature additions. It differentiates itself by being the officially supported, feature-rich, and actively maintained interactive shell for MongoDB, offering advanced features like schema sampling, streaming processor attributes, and improved authentication mechanisms compared to older MongoDB shells.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates global installation, connection to MongoDB, inserting and querying data using the `mongosh` CLI, and executing a JavaScript file containing shell commands.

// This quickstart demonstrates using the mongosh CLI, not programmatic Node.js imports.
// First, ensure mongosh is installed globally via npm:
// npm install -g mongosh

// From your terminal, connect to a local MongoDB instance and insert a document:
mongosh "mongodb://localhost:27017/testdb" \
  --eval "db.collection('mycollection').insertOne({ item: 'notebook', qty: 50, tags: ['stationery', 'office'] })"

// Then, query the inserted document using --json for structured output:
mongosh "mongodb://localhost:27017/testdb" \
  --eval "db.collection('mycollection').find({ item: 'notebook' }).toArray()" \
  --json=relaxed

// For scripting, you can place shell commands into a JavaScript file (e.g., my_script.js):
// // my_script.js
// const conn = new Mongo('mongodb://localhost:27017/anotherdb');
// const db = conn.getDB('anotherdb');
// db.collection('documents').insertOne({ date: new Date(), message: 'Hello from mongosh script!' });
// printjson(db.collection('documents').findOne());

// And execute it via the CLI:
// mongosh my_script.js

view raw JSON →