How to Use the MongoDB mongo Command

This article explains how to connect using mongo, the client module for connecting to MongoDB.

Basic options

Option Description
--host <hostname> Specifies the host name of the MongoDB server to connect to. If no host name is specified, it connects to localhost.
--port <port> Specifies the port number used to connect to the MongoDB server. If no port number is specified, it connects to 27017.
--username <username>, -u <username> Specifies the user name when accessing MongoDB with authentication enabled.
--password <password>, -p <password> Specifies the password when connecting to MongoDB with authentication enabled.
--authenticationDatabase <dbname> Specifies the database name used for authentication.

Files

.dbshell

This stores the history of commands executed in the mongo shell. The file is automatically created directly under the home directory (%UserProfile%). On Windows, for example, it is located in the following place.

%UserProfile%

C:\Users\<user name>\.dbshell

.mongorc.js

If you place the .mongorc.js file directly under a defined directory (%UserProfile% or %ProgramData%), .mongorc.js is automatically loaded and executed when mongo starts. This lets you predefine variables or functions that you want to use commonly while the shell is running. .mongorc.js reads global definitions (%ProgramData%) before user definitions (%UserProfile%).

If you do not want to load .mongorc.js, start mongo with the --norc option.

On Windows, for example, the directories are as follows. %UserProfile%

C:\Users\<user name>\.mongorc.js

%ProgramData%

C:\ProgramData\MongoDB\.mongorc.js

References