Docs HomeMongoDB Shell

Run Commands运行命令

To run commands in mongosh, you must first connect to a MongoDB deployment.要在mongosh中运行命令,必须首先连接到MongoDB部署。

Switch Databases交换机数据库

To display the database you are using, type db:要显示您正在使用的数据库,请键入db

db

The operation should return test, which is the default database.操作应该返回test,这是默认的数据库。

To switch databases, issue the use <db> helper, as in the following example:要切换数据库,请发出use <db>,如下例所示:

use <database>

To access a different database from the current database without switching your current database context, see the db.getSiblingDB() method.要在不切换当前数据库上下文的情况下访问与当前数据库不同的数据库,请参阅db.getSiblingDB()方法。

To list the databases available to the user, use the helper show dbs.要列出用户可用的数据库,请使用helper show dbs

Create a New Database and Collection创建新数据库和集合

To create a new database, issue the use <db> command with the database that you would like to create. 要创建新数据库,请对要创建的数据库发出use <db>命令。For example, the following commands create both the database myNewDatabase and the collection myCollection using the insertOne() operation:例如,以下命令使用insertOne()操作创建数据库myNewDatabase集合myCollection

use myNewDatabase
db.myCollection.insertOne( { x: 1 } );

If a collection does not exist, MongoDB creates the collection when you first store data for that collection.如果某个集合不存在,MongoDB会在您第一次存储该集合的数据时创建该集合。

Terminate a Running Command终止正在运行的命令

To terminate a running command or query in mongosh, press Ctrl + C.要终止mongosh中正在运行的命令或查询,请按Ctrl+C

When you enter Ctrl + C, mongosh:当您输入Ctrl+C时,mongosh

  • interrupts the active command,中断激活的命令,
  • tries to terminate the ongoing, server-side operation, and尝试终止正在进行的服务器端操作,并且
  • returns a command prompt.返回命令提示符。

If mongosh cannot cleanly terminate the running process, it issues a warning.如果mongosh无法干净地终止正在运行的进程,它将发出警告。

Note

Pressing Ctrl + C in mongosh does not terminate asynchronous code. mongosh中按Ctrl+C不会终止异步代码。Asynchronous operations such as setTimeout or operations like fs.readFile continue to run.诸如setTimeout之类的异步操作或诸如fs.readFile之类的操作将继续运行。

There is no way to terminate asynchronous code in mongosh. 没有办法终止mongosh中的异步代码。This is the same behavior as in the Node.js REPL.这与Node.js REPL.中的行为相同。

Pressing Ctrl + C once will not exit mongosh, press Ctrl + C twice to exit mongosh.Ctrl+C一次不会退出mongosh,按Ctrl+C两次退出mongoh

Command Exceptions命令异常

In scenarios where the output of a command includes { ok: 0 }, mongosh throws an exception and does not return the raw output from the server.在命令输出包括{ ok: 0 }的场景中,mongosh抛出异常,并且不返回服务器的原始输出。

Note

In the legacy mongo shell, when a command's output included { ok: 0 }, the behavior differs between commands. 在遗留的mongoshell中,当命令的输出包含{ ok: 0 }时,不同命令的行为不同。mongosh provides consistent behavior by always throwing an exception in these scenarios.mongosh通过在这些场景中总是抛出异常来提供一致的行为。

Clear the mongosh Console清除mongosh控制台

The cls command clears the console. You can also clear the console with Ctrl + L and console.clear().cls命令清除控制台。您也可以使用Ctrl+Lconsole.clear()清除控制台。