Docs HomeMongoDB Shell

Write Scripts写入脚本

You can write scripts for the MongoDB Shell that modify data in MongoDB or perform administrative operations. 您可以为MongoDB Shell编写脚本,修改MongoDB中的数据或执行管理操作。You may also want to package your scripts as snippets for easier distribution and management.您可能还希望将脚本打包为snippets,以便更容易地分发和管理。

This tutorial introduces using the MongoDB Shell with JavaScript to access MongoDB.本教程介绍使用带有JavaScript的MongoDB Shell访问MongoDB。

Execute a JavaScript File执行JavaScript文件

Execute a Script from Within mongoshmongosh内部执行脚本

You can execute a .js file from within the MongoDB Shell using the load() method.您可以使用load()方法从MongoDB Shell中执行一个.js文件。

File Paths文件路径

The load() method accepts relative and absolute paths. load()方法接受相对路径和绝对路径。If the current working directory of the MongoDB Shell is /data/db, and connect-and-insert.js is in the /data/db/scripts directory, then the following calls within the MongoDB Shell are equivalent:如果MongoDB Shell当前的工作目录是/data/dbconnect-and-insert.js/data/db/scripts目录中,那么MongoDB Shell中的以下调用是等效的:

load( "scripts/connect-and-insert.js" )
load( "/data/db/scripts/connect-and-insert.js" )

Example实例

The following example creates and executes a script that:以下示例创建并执行一个脚本:

  • Connects to a local instance running on the default port.连接到在默认端口上运行的本地实例。
  • Connects to the myDatabase database.连接到myDatabase数据库。
  • Populates the movies collection with sample documents.使用示例文档填充movies集合。
  1. Create a file named connect-and-insert.js with the following contents:创建一个名为connect-and-insert.js的文件,其中包含以下内容:

    db = connect( 'mongodb://localhost/myDatabase' );

    db.movies.insertMany( [
    {
    title: 'Titanic',
    year: 1997,
    genres: [ 'Drama', 'Romance' ]
    },
    {
    title: 'Spirited Away',
    year: 2001,
    genres: [ 'Animation', 'Adventure', 'Family' ]
    },
    {
    title: 'Casablanca',
    genres: [ 'Drama', 'Romance', 'War' ]
    }
    ] )
  2. To load and execute the connect-and-insert.js file, use mongosh to connect to your deployment and run the following command:要加载并执行connect-and-insert.js文件,请使用mongosh连接到您的部署并运行以下命令:

    load( "connect-and-insert.js" )
  3. To confirm that the documents loaded correctly, use the myDatabase collection and query the movies collection.要确认文档加载正确,请使用myDatabase集合并查询movies集合。

    use myDatabase
    db.movies.find()
Note

There is no search path for the load() method. load()方法没有搜索路径。If the target script is not in the current working directory or the full specified path, the MongoDB Shell cannot access the file.如果目标脚本不在当前工作目录或指定的完整路径中,MongoDB Shell将无法访问该文件。

Execute a Script From the Command Line从命令行执行脚本

You can use mongosh to execute a script from the command line without entering the mongosh console.您可以使用mongosh从命令行执行脚本,而无需进入mongosh控制台。

To specify the filename, use the --file or -f parameter to specify the filename. 要指定文件名,请使用--file-f参数指定文件名。You may also need to specify connection information in addition to the --file or -f parameters.除了--file-f参数之外,您可能还需要指定连接信息。

Tip

If you pass a filename to mongosh without using the parameter flags the connection may fail if there are other command line arguments.如果在不使用参数标志的情况下将文件名传递给mongosh,则如果存在其他命令行参数,则连接可能会失败。

To pass filenames always use --file or -f.要传递文件名,请始终使用--file-f

Example实例

The following example creates scripts and runs them from the command line.以下示例创建脚本并从命令行运行它们。

  1. Copy this script and save it as loadMovies.js.复制此脚本并将其另存为loadMovies.js

    db = connect( 'mongodb://localhost/films' );

    db.movies.insertMany( [
    {
    title: 'Titanic',
    year: 1997,
    genres: [ 'Drama', 'Romance' ]
    },
    {
    title: 'Spirited Away',
    year: 2001,
    genres: [ 'Animation', 'Adventure', 'Family' ]
    },
    {
    title: 'Casablanca',
    genres: [ 'Drama', 'Romance', 'War' ]
    }
    ] )
    Tip

    Verify the connection string in the highlighted line. 验证高亮显示的行中的连接字符串。If your MongoDB instance is not running on localhost:27017, you must edit the connection string.如果您的MongoDB实例没有在localhost:27017上运行,则必须编辑连接字符串。

    For example, the following connection string connects to localhost port 27500:例如,以下连接字符串连接到localhost端口27500

    db = connect( 'mongodb://localhost:27500/films' );
  2. Copy this script and save it as queryMovies.js.复制此脚本并将其另存为queryMovies.js

    db = connect( 'mongodb://localhost/films' );
    printjson( db.movies.find( {} ) );
  3. Run the scripts from the command line.从命令行运行脚本。

    mongosh --file loadMovies.js --file queryMovies.js
  4. Verify the output.验证输出。

    Loading file: loadMovies.js
    Loading file: queryMovies.js
    [
    {
    _id: ObjectId("616f1b8092dbee425b661117"),
    title: 'Titanic',
    year: 1997,
    genres: [ 'Drama', 'Romance' ]
    },
    {
    _id: ObjectId("616f1b8092dbee425b661118"),
    title: 'Spirited Away',
    year: 2001,
    genres: [ 'Animation', 'Adventure', 'Family' ]
    },
    {
    _id: ObjectId("616f1b8092dbee425b661119"),
    title: 'Casablanca',
    genres: [ 'Drama', 'Romance', 'War' ]
    }
    ]

    The output of the db.collection.find() command shows that the movies collection was updated.db.collection.find()命令的输出显示movies集合已更新。

    Tip

    To make the output visible, use printjson() to call db.collection.find().要使输出可见,请使用printjson()调用db.collection.find()

    printjson( db.movies.find( {} ) ) ;

Execute a Script From the Command Line with Authentication通过身份验证从命令行执行脚本

To execute a script against a remote mongod instance that requires authentication, specify the connection and authentication details in addition to the filename.要针对需要身份验证的远程mongod实例执行脚本,除了指定文件名外,还应指定连接和身份验证详细信息。

For example:例如:

mongosh --host 172.17.0.3 --port 27500 --username filmFan --password superSecret --file loadMovies.js

You can also specify the shortened form of the options:您还可以指定选项的缩写形式:

mongosh --host 172.17.0.3 --port 27500 -u filmFan -p superSecret -f loadMovies.js
Tip

In shells like bash and zsh, if you begin a command with a space it will not be saved in your command history. bashzsh这样的shell中,如果用空格开始一个命令,它将不会保存在命令历史记录中。This minimizes exposure if you enter passwords on the command line.如果您在命令行中输入密码,这样可以最大限度地减少暴露。

Execute Code From a Configuration File从配置文件执行代码

On startup, mongosh checks your HOME directory for a JavaScript file named .mongoshrc.js. If this file is found, mongosh reads the content of .mongoshrc.js before displaying the prompt for the first time.启动时,mongosh会在HOME目录中检查一个名为.mongoshrc.js的JavaScript文件。如果找到这个文件,mongosh会在第一次显示提示之前读取.mongoshrc.js的内容。

Execute JavaScript Code执行JavaScript代码

To update the mongosh prompt to display line numbers, add the following code to <your-home-directory>/.mongoshrc.js要更新mongosh提示符以显示行号,请将以下代码添加到<your-home-directory>/.mongoshrc.js

let cmdCount = 1;
prompt = function() {
return (cmdCount++) + "> ";
}

The prompt will look like this:提示如下所示:

1> show collections
2> use test
3>

Execute MongoDB Code执行MongoDB代码

To create a log of when your mongosh client connects to a database, add the following code to <your-home-directory>/.mongoshrc.js:要创建mongosh客户端何时连接到数据库的日志,请将以下代码添加到<your-home-directory>/.mongoshrc.js

db.clientConnections.insertOne( { connectTime: ISODate() } )

Each time you connect to a database, the MongoDB server adds a document like the following to the clientConnections collection.每次连接到数据库时,MongoDB服务器都会向clientConnections集合中添加如下文档。

{
_id: ObjectId("61d4bbf0fa4c85f53418070f"),
connectTime: ISODate("2022-01-04T21:28:16.367Z")
}

Execute JavaScript and MongoDB Code执行JavaScript和MongoDB代码

The current database name is part of the default mongosh prompt. 当前数据库名称是默认mongosh提示的一部分。To reformat the prompt to show the database and hostname, use a function like this one:要重新格式化提示以显示数据库和主机名,请使用以下函数:

{
const hostnameSymbol = Symbol('hostname');
prompt = () => {
if (!db[hostnameSymbol])
db[hostnameSymbol] = db.serverStatus().host;
return `${db.getName()}@${db[hostnameSymbol]}> `;
};
}

The prompt will look like this:提示如下所示:

admin@centos0722:27502>

Open a New Connection打开新连接

From the MongoDB Shell or from a JavaScript file, you can instantiate database connections using the Mongo() method:从MongoDB Shell或JavaScript文件中,可以使用Mongo()方法实例化数据库连接:

new Mongo()
new Mongo(<host>)
new Mongo(<host:port>)
Note

The MongoDB Shell does not support the ClientSideFieldLevelEncryptionOptions document with the Mongo() method.MongoDB Shell不支持使用Mongo()方法的ClientSideFieldLevelEncryptionOptions文档。

Connect to a Local MongoDB Instance连接到本地MongoDB实例

Consider a MongoDB instance running on localhost on the default port.考虑在默认端口的localhost上运行一个MongoDB实例。

The following example:以下示例:

  • Instantiates a new connection to the instance, and实例化到实例的新连接,并且
  • Sets the global db variable to myDatabase using the Mongo.getDB() method.使用Mongo.getDB()方法将全局db变量设置为myDatabase。
conn = Mongo();
db = conn.getDB("myDatabase");

Connect to a MongoDB Instance that Enforces Access Control连接到强制访问控制的MongoDB实例

To connect to a MongoDB instance that enforces access control, you must include the credentials in the connection string.要连接到强制访问控制的MongoDB实例,必须在连接字符串中包含凭据。

The following command connects to a MongoDB instance that is:以下命令连接到一个MongoDB实例,该实例为:

  • Running on localhost on the default port, and在默认端口的localhost上运行,并且
  • Secured using SCRAM.使用SCRAM进行固定。
conn = Mongo("mongodb://<username>:<password>@localhost:27017/<authDB>");
Note

The MongoDB Shell redacts credentials from the command history and the logs.MongoDB Shell对命令历史记录日志中的凭据进行编辑。

Use connect() to Connect to a MongoDB Instance使用connect()连接到MongoDB实例

You can also use the connect() method to connect to the MongoDB instance.您还可以使用connect()方法连接到MongoDB实例。

The following command:以下命令:

  • Connects to the MongoDB instance that is running on localhost with the non-default port 27020, and使用非默认端口27020连接到在localhost上运行的MongoDB实例,并且
  • Sets the global db variable.设置全局db变量。
db = connect("localhost:27020/myDatabase");

Connection Considerations连接注意事项

Consider portability and the operating environment when you write scripts.在编写脚本时,请考虑可移植性和操作环境。

Script Includes Connection Detail脚本包括连接详细信息

If the connection details are included in the script:如果脚本中包含连接详细信息:

  • You do not need to specify connection information on the command line.不需要在命令行中指定连接信息。
  • You should use the --nodb parameter.您应该使用--nodb参数。

Consider a mongod instance running on localhost:27500.考虑一个在localhost:27500上运行的mongod实例。

The following script prints the number of users. 以下脚本打印用户数。Copy the code and save it as getUserCount.js.复制代码并将其保存为getUserCount.js

db = connect( "localhost:27500/admin" );˘
printjson( db.system.users.countDocuments() );

Run getUserCount.js:运行getUserCount.js

mongosh --nodb --file getUserCount.js
  • mongosh defaults to port 27170.默认为端口27170。
  • mongod is running on port 27500.正在端口27500上运行。
  • The --nodb parameter instructs mongosh to run a script without first connecting to a mongod instance.--nodb参数指示mongosh在不首先连接到mongod实例的情况下运行脚本。

The highlighted line is correct, but getUserCount.js will not run without --nodb because mongosh cannot connect to the local instance. 突出显示的行是正确的,但是getUserCount.js在没有--nodb的情况下不会运行,因为mongosh无法连接到本地实例。With --nodb, mongosh runs getUserCount.js and uses the highlighted information to connect.使用--nodbmongosh运行getUserCount.js并使用突出显示的信息进行连接。

Script Does Not Include Connection Details脚本不包括连接详细信息

It is convenient to specify connection information in your script, but that also makes it less portable. 在脚本中指定连接信息很方便,但这也降低了它的可移植性。The getUserCount.js script would have to be updated to run on a remote instance or one running on a different port.getUserCount.js脚本必须更新才能在远程实例或其他端口上运行。

To increase portability, use db.getSiblingDB() and specify the connection information on the command line.为了提高可移植性,请使用db.getSiblingDB()并在命令行中指定连接信息。

The following script is more portable than getUserCount.js because it does not have specific connection details. 以下脚本比getUserCount.js更易于移植,因为它没有特定的连接详细信息。Copy the code and save it as portableGetUserCount.js.复制代码并将其保存为portableGetUserCount.js

db = db.getSiblingDB( "admin" );
printjson( db.system.users.countDocuments() );

To run portableGetUserCount.js, specify the host and port on the command line:要运行portableGetUserCount.js,请在命令行中指定主机和端口:

mongosh --host 172.17.0.3 --port 27500 --file portableGetUserCount.js

To run portableGetUserCount.js on a different host or port, change the connection details on the command line. 要在其他主机或端口上运行portableGetUserCount.js,请在命令行中更改连接详细信息。Unlike getUserCount.js, you do not have to edit the script to run portableGetUserCount.js.getUserCount.js不同,您不必编辑脚本即可运行portableGetUserCount.js