Run Commands运行命令
On this page本页内容
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 要列出用户可用的数据库,请使用helper show dbs
.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时,Ctrl + C
, mongosh
: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
无法干净地终止正在运行的进程,它将发出警告。
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一次不会退出Ctrl + C
once will not exit mongosh
, press Ctrl + C
twice to exit mongosh
.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
抛出异常,并且不返回服务器的原始输出。
In the legacy 在遗留的mongo
shell, when a command's output included { ok: 0 }
, the behavior differs between commands. mongo
shell中,当命令的输出包含{ ok: 0 }
时,不同命令的行为不同。mongosh
provides consistent behavior by always throwing an exception in these scenarios.mongosh
通过在这些场景中总是抛出异常来提供一致的行为。
Clear the mongosh
Console清除mongosh
控制台
mongosh
ConsoleThe cls
command clears the console. You can also clear the console with Ctrl + L
and console.clear()
.cls
命令清除控制台。您也可以使用Ctrl+L和console.clear()
清除控制台。