Get the App
SLTechnology News&Howtos  ›  Database  › 

[teacher Zhao Qiang] use MongoDB's command line tool: mongoshell

Shulou Source: shulou.com Published: 2022-06-01 05:19:43 09月30日 Update

Start the mongo shell.

After MongoDB is installed, execute the following command directly from the command line terminal:

mongo

As shown below:

Optional parameters are as follows:

It can also be abbreviated as:

To use an external editor in the mongo shell, such as vi, simply set the environment variable:

export EDITOR=vi

Start mongo shel. Here we edit a function in mongoshell:

Definition function:

function myFunction () { }

Edit functions:

edit myFunctionfunction myFunction() {print("Hello World") } Second, mongoshell startup configuration file.mongorc.js

When started, mongo checks for a JavaScript file named.mongorc.js in the user's HOME directory. If found, mongo parses the contents of. mongorc.js before first displaying the prompt. If you execute a JavaScript file or evaluate an expression using the shell, either by using the-eval option on the command line or by specifying a.js file to mongo, mongo will read the. mongorc.js file after the JavaScript has been processed. You can prevent. mongorc.js from loading by using the-norc option.

Create a prompt for the number of actions issued with the current session, defining the following variables:

cmdCount = 1;prompt = function() { return "mongo " + (cmdCount++) + "> ";} The effect is as follows:

Display database name and host name in mongo shell:

host = db.serverStatus().host;cmdCount = 1;prompt = function() { return db+"@"+host+" " + (cmdCount++) + "> ";} The effect is as follows:

Basic Operation of Mongoshell

To display the current database name, enter the following command. The test database is returned, which is the default database:

db

Switch database:

use

View all available databases:

show dbs or show databases

We can switch to a database that doesn't exist. MongoDB automatically creates the database the first time we store it. For example, the following example inserts a piece of data that creates both database (myNewDatabase) and collection (myCollection).

Tags: Data database file command function facet variable effect time switch prompt host example information content parameter just at the same time name basic operation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Linux Huawei MariaDB OPPO Reno