Create New Post

MongoDB - Mongosh

 

Mongosh is the official command-line shell for MongoDB. It provides a user-friendly and interactive environment for interacting with MongoDB databases and clusters. mongosh is designed to offer a modern and powerful interface, making it easy for developers and administrators to work with MongoDB.

Installation:

  • Installation via npm:

    npm install -g mongodb
    
  • Installation via Homebrew (on macOS):

    brew tap mongodb/brew
    brew install mongosh
     
  • Installation via Chocolatey (on Windows):

    choco install mongosh
     

Connecting to MongoDB:

  • Connect to a MongoDB Server:

    mongosh mongodb://hostname:port/database
     
  • Connect to a MongoDB Atlas Cluster:

    mongosh "mongodb+srv://<username>:<password>@<cluster-address>/test?retryWrites=true&w=majority"
     

Basic Usage:

  • Query Documents:

    db.collection_name.find();
    
    
  • Insert Documents:

    db.collection_name.insertOne({ field1: value1, field2: value2 });
     
  • Update Documents:

    db.collection_name.updateOne({ field: value }, { $set: { updated_field: new_value } });
     
  • Delete Documents:

    db.collection_name.deleteOne({ field: value });
     

Interactive Features:

  • Autocompletion: mongosh supports autocompletion for MongoDB commands and JavaScript functions.

  • Syntax Highlighting: Code snippets are syntax-highlighted for better readability.

  • Integrated Help: Access documentation and help directly from the shell.

Built-in Commands:

  • show dbs: List available databases.
  • use <database>: Switch to a specific database.
  • show collections: List collections in the current database.
  • db.version(): Display the MongoDB server version.

Scripting and Automation:

  • Run Scripts: Execute JavaScript files using the load() function.

    load('path/to/script.js');
     
  • Save Output: Save query results to a file.

    db.collection_name.find().toArray().forEach(printjson);
     

Exiting mongosh:

  • Exit the Shell:

    exit
     
  • Keyboard Shortcut: Press Ctrl + D to exit.

mongosh provides a powerful and user-friendly interface for interacting with MongoDB, and it's continually evolving with updates and improvements.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

79211