[Mr. Zhao Qiang] use mongodb’s command line tool: mongoshell


1、 Start Mongo shell

After mongodb is installed, execute the following commands directly on the command line terminal:


As shown in the figure below:

The optional parameters are as follows:

It can also be abbreviated as:

To use an external editor in Mongo shell, such as: VI, you only need to set the environment variable:

export EDITOR=vi

Start Mongo shell. Let’s edit a function in Mongo shell:

Define function:

function myFunction () { }

Edit function:

edit myFunction
function myFunction() {print("Hello World") }

2、 Startup configuration file for Mongo shell. Mongorc.js

When started, Mongo checks a JavaScript file. Mongorc. JS in the user’s home directory. If found, Mongo parses the contents of. Mongorc.js before displaying the prompt for the first time. If you use the shell to execute a JavaScript file or calculation expression, either use the — Eval option on the command line or specify a. JS file to Mongo. Mongo will read the. Mongorc.js file after JavaScript processing. You can use the — NORC option to prevent loading. Mongorc. JS.

  • Create a prompt for the number of operations issued with the current session, and define the following variables:
cmdCount = 1;
prompt = function() {
    return "mongo " + (cmdCount++) + "> ";

The effects are as follows:

  • Display the database name and host name in the Mongo shell:
host = db.serverStatus().host;
cmdCount = 1;
prompt = function() {
    return db+"@"+host+" " + (cmdCount++) + "> ";

The effects are as follows:

3、 Basic operation of Mongo shell

  • To display the current database name, enter the following command. The test database is returned, which is the default database:
  • Switch database:
  • View all available databases:
Show DBS or show databases
  • We can switch to a nonexistent database. When we store data for the first time, mongodb will automatically create the database. For example, the following example inserts a piece of data, which will create both database (mynewdatabase) and collection (mycollection)


Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]