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 Instanceconnect()
连接到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连接到myDatabase
database.myDatabase
数据库。Populates the使用示例文档填充movies
collection with sample documents.movies
集合。
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' ]
}
] )To load and execute the要加载并执行connect-and-insert.js
file, usemongosh
to 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要确认文档加载正确,请使用myDatabase
collection and query themovies
collection.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' ]
}
] )TipVerify 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例如,以下连接字符串连接到localhost
port27500
: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 thedb.collection.find()
command shows that themovies
collection was updated.db.collection.find()
命令的输出显示movies
集合已更新。TipTo make the output visible, use要使输出可见,请使用printjson()
to calldb.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
TipIn shells like在bash
andzsh
, 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,启动时,mongosh
checks yourHOME
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
的内容。TipExecute 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每次连接到数据库时,MongoDB服务器都会向clientConnections
collection.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从MongoDB Shell或JavaScript文件中,可以使用Mongo()
method:Mongo()
方法实例化数据库连接:new Mongo()
new Mongo(<host>)
new Mongo(<host:port>)NoteThe 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使用db
variable tomyDatabase
using theMongo.getDB()
method.Mongo.getDB()
方法将全局db
变量设置为myDatabas
e。
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>");
NoteThe MongoDB Shell redacts credentials from the command history and the logs.MongoDB Shell对命令历史记录和日志中的凭据进行编辑。Use使用connect()
to Connect to a MongoDB Instanceconnect()
连接到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 port27020
, and27020
连接到在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 onlocalhost: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 instructsmongosh
to run a script without first connecting to amongod
instance.--nodb
参数指示mongosh
在不首先连接到mongod
实例的情况下运行脚本。
The highlighted line is correct, but突出显示的行是正确的,但是getUserCount.js
will not run without--nodb
becausemongosh
cannot connect to the local instance.getUserCount.js
在没有--nodb
的情况下不会运行,因为mongosh
无法连接到本地实例。With使用--nodb
,mongosh
runsgetUserCount.js
and 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.在脚本中指定连接信息很方便,但这也降低了它的可移植性。ThegetUserCount.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 runportableGetUserCount.js
.getUserCount.js
不同,您不必编辑脚本即可运行portableGetUserCount.js
。