Write Scripts写入脚本
On this page本页内容
- Execute a JavaScript File执行JavaScript文件
- Execute a Script from Within mongosh从- mongosh内部执行脚本
- Execute a Script From the Command Line从命令行执行脚本
- Execute a Script From the Command Line with Authentication通过身份验证从命令行执行脚本
- Execute Code From a Configuration File从配置文件执行代码
- Execute JavaScript Code执行JavaScript代码
- Execute MongoDB Code执行MongoDB代码
- Execute JavaScript and MongoDB Code执行JavaScript和MongoDB代码
- Open a New Connection打开新连接
- Connect to a Local MongoDB Instance连接到本地MongoDB实例
- Connect to a MongoDB Instance that Enforces Access Control连接到强制访问控制的MongoDB实例
- Use使用- connect()to Connect to a MongoDB Instance- connect()连接到MongoDB实例
- Connection Considerations连接注意事项
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 mongosh从mongosh内部执行脚本
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 如果MongoDB Shell当前的工作目录是/data/db, and connect-and-insert.js is in the /data/db/scripts directory, then the following calls within the MongoDB Shell are equivalent:/data/db,connect-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连接到- myDatabasedatabase.- myDatabase数据库。
- Populates the使用示例文档填充- moviescollection with sample documents.- movies集合。
- Create a file named创建一个名为- connect-and-insert.jswith 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' ]
 }
 ] )
- To load and execute the要加载并执行- connect-and-insert.jsfile, use- mongoshto connect to your deployment and run the following command:- connect-and-insert.js文件,请使用- mongosh连接到您的部署并运行以下命令:- load( "connect-and-insert.js" ) 
- To confirm that the documents loaded correctly, use the要确认文档加载正确,请使用- myDatabasecollection and query the- moviescollection.- myDatabase集合并查询- movies集合。- use myDatabase 
 db.movies.find()
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参数之外,您可能还需要指定连接信息。
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.以下示例创建脚本并从命令行运行它们。
- loadMovies.js- , uses,使用- insertMany()to a update a local MongodDB instance.- insertMany()来更新本地MongoDB实例。
- queryMovies.js- uses使用- db.collection.find()to verify the update.- db.collection.find()验证更新。
- 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如果您的MongoDB实例没有在- localhost:27017, you must edit the connection string.- localhost:27017上运行,则必须编辑连接字符串。- For example, the following connection string connects to例如,以下连接字符串连接到- localhostport- 27500:- localhost端口- 27500:- db = connect( 'mongodb://localhost:27500/films' ); - Copy this script and save it as复制此脚本并将其另存为- queryMovies.js.- queryMovies.js。- db = connect( 'mongodb://localhost/films' ); 
 printjson( db.movies.find( {} ) );- Run the scripts from the command line.从命令行运行脚本。- mongosh --file loadMovies.js --file queryMovies.js - 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- moviescollection 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要针对需要身份验证的远程- mongodinstance 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在- bashand- zsh, if you begin a command with a space it will not be saved in your command history.- bash和- zsh这样的shell中,如果用空格开始一个命令,它将不会保存在命令历史记录中。- This minimizes exposure if you enter passwords on the command line.如果您在命令行中输入密码,这样可以最大限度地减少暴露。- Execute Code From a Configuration File从配置文件执行代码- On startup,启动时,- mongoshchecks your- HOMEdirectory for a JavaScript file named- .mongoshrc.js. If this file is found,- mongoshreads the content of- .mongoshrc.jsbefore displaying the prompt for the first time.- mongosh会在- HOME目录中检查一个名为- .mongoshrc.js的JavaScript文件。如果找到这个文件,- mongosh会在第一次显示提示之前读取- .mongoshrc.js的内容。Tip- Execute JavaScript Code执行JavaScript代码- To update the要更新- mongoshprompt 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要创建- mongoshclient 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每次连接到数据库时,MongoDB服务器都会向- clientConnectionscollection.- 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当前数据库名称是默认- mongoshprompt.- 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从MongoDB Shell或JavaScript文件中,可以使用- Mongo()method:- Mongo()方法实例化数据库连接:- new Mongo() 
 new Mongo(<host>)
 new Mongo(<host:port>)Note- The MongoDB Shell does not support the ClientSideFieldLevelEncryptionOptions document with theMongoDB Shell不支持使用- Mongo()method.- 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使用- dbvariable to- myDatabaseusing 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实例,该实例为:- 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使用非默认端口- localhostwith the non-default port- 27020, and- 27020连接到在- localhost上运行的MongoDB实例,并且
- Sets the global设置全局- dbvariable.- 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您应该使用- --nodbparameter.- --nodb参数。
 - Consider a考虑一个在- mongodinstance 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- --nodbparameter instructs- mongoshto run a script without first connecting to a- mongodinstance.- --nodb参数指示- mongosh在不首先连接到- mongod实例的情况下运行脚本。
 - The highlighted line is correct, but突出显示的行是正确的,但是- getUserCount.jswill not run without- --nodbbecause- mongoshcannot connect to the local instance.- getUserCount.js在没有- --nodb的情况下不会运行,因为- mongosh无法连接到本地实例。- With使用- --nodb,- mongoshruns- getUserCount.jsand uses the highlighted information to connect.- --nodb,- mongosh运行- 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.jsscript 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.jsbecause 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.json 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。