翻译或纠错本页面

Write Scripts for the mongo Shell

You can write scripts for the mongo shell in JavaScript that manipulate data in MongoDB or perform administrative operation. For more information about the mongo shell, see the Running .js files via a mongo shell Instance on the Server section for more information about using these mongo script.

This tutorial provides an introduction to writing JavaScript that uses the mongo shell to access MongoDB.

打开新连接

mongo shell 或者 JavaScript文件中,你可以使用 Mongo() 构造函数来实例化数据库连接:

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

考虑下面的示例,实例化一个到本机默认端口上运行的MongoDB实例的新连接,并且使用 getDB() 方法将全局的 db 变量设置为 myDatabase

conn = new Mongo();
db = conn.getDB("myDatabase");

如果连接到一个需要读取控制的MongoDB实例,你可以使用 db.auth() 方法进行授权。

此外,你可以使用 connect() 方法连接到MongoDB实例。下面的示例 连接到运行在 localhost 非默认端口 27020 上的MongoDB实例,并且设置了全局的 db 变量:

db = connect("localhost:27020/myDatabase");

交互式和脚本化 mongo 的区别

When writing scripts for the mongo shell, consider the following:

  • 为了设置 db 全局变量,使用 getDB() 或者 connect() 方法。你可以将数据库引用复制给除了``db`` 之外的变量。

  • Write operations in the mongo shell use a write concern of { w: 1 } by default. If performing bulk operations, use the Bulk() methods. See Write Method Acknowledgements for more information.

    在 2.6 版更改: Before MongoDB 2.6, call db.getLastError() explicitly to wait for the result of write operations.

  • 不能 在JavaScript文件中使用任何shell帮助 (例如,use <dbname>`, ``show dbs `` 等),因为它们都不是合法的JavaScript。

    下面的表格中将最常见的 mongo shell帮助映射到它们对应的JavaScript。

    Shell 帮助

    JavaScript 等量

    show dbs, show databases
    db.adminCommand('listDatabases')
    
    use <db>
    db = db.getSiblingDB('<db>')
    
    show collections
    db.getCollectionNames()
    
    show users
    db.getUsers()
    
    show roles
    db.getRoles({showBuiltinRoles: true})
    
    show log <logname>
    db.adminCommand({ 'getLog' : '<logname>' })
    
    show logs
    db.adminCommand({ 'getLog' : '*' })
    
    it
    cursor = db.collection.find()
    if ( cursor.hasNext() ){
       cursor.next();
    }
    
  • 在交互模式中, mongo 打印出包括所有游标内容在内的操作结果。在脚本中,使用 JavaScript print() 函数或者 mongo 中特定的 printjson 函数返回形式化的JSON。

    示例

    为了打印出 mongo shell脚本中结果游标的所有条目,使用下列命令:

    cursor = db.collection.find();
    while ( cursor.hasNext() ) {
       printjson( cursor.next() );
    }
    

脚本

根据系统提示,使用 mongo 来计算 JavaScript的值。

--eval 选项

Use the --eval option to mongo to pass the shell a JavaScript fragment, as in the following:

mongo test --eval "printjson(db.getCollectionNames())"

这将返回使用 mongo shell 连接到运行在 localhost 接口 27017 端口上 mongodmongos 实例的 db.getCollectionNames() 输出。

执行JavaScript文件

你可以想 mongo shell 指定一个 .js 文件, mongo 将会直接运行JavaScript。考虑下面的示例:

mongo localhost:27017/test myjsfile.js

该操作在连接到``localhost`` 接口 27017 端口 mongod 实例上 test database 的:program:mongo shell 中执行 myjsfile.js 脚本。

相应地,你可以使用javascript文件中的 Mongo() 构造函数来指定mongodb连接草书。 查阅 打开新连接 了解更多信息。

你可以在 mongo shell 中使用 load() 函数运行 .js 文件,如下所示:

load("myjstest.js")

该函数导入并运行了 myjstest.js 文件。

load() 方法可接受相对路径和绝对路径。如果 mongo shell 当前的工作目录位于 /data/db, 而文件 myjstest.js 位于 /data/db/scripts 目录,那么下面两种在 mongo 中的调用将会等价。

load("scripts/myjstest.js")
load("/data/db/scripts/myjstest.js")

注解

There is no search path for the load() function. If the desired script is not in the current working directory or the full specified path, mongo will not be able to access the file.