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.

Opening New Connections

From the mongo shell or from a JavaScript file, you can instantiate database connections using the Mongo()constructor:

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

Consider the following example that instantiates a new connection to the MongoDB instance running on localhost on the default port and sets the global db variable to myDatabase using the getDB() method:

> conn = new Mongo();
2016-12-01T00:09:03.664+0800 I NETWORK [initandlisten] connection accepted from 127.0.0.1:29118 #8 (8 connections now open)
connection to 127.0.0.1
> db = conn.getDB("myDatabase");
myDatabase

If connecting to a MongoDB instance that enforces access control, you can use the db.auth() method to authenticate.

Additionally, you can use the connect() method to connect to the MongoDB instance. The following example connects to the MongoDB instance that is running on localhost with the non-default port 27020and set the global db variable:

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

SEE ALSO: mongo Shell Methods

Differences Between Interactive and Scripted mongo

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

  • To set the db global variable, use the getDB() method or the connect() method. You can assign the database reference to a variable other than 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.

    Changed in version 2.6: Before MongoDB 2.6, call db.getLastError() explicitly to wait for the result of write operations.

  • You cannot use any shell helper (e.g. use <dbname>, show dbs, etc.) inside the JavaScript file because they are not valid JavaScript.

    The following table maps the most common mongo shell helpers to their JavaScript equivalents.

    Shell Helpers JavaScript Equivalents
     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();
     }

  • In interactive mode, mongo prints the results of operations including the content of all cursors. In scripts, either use the JavaScript print() function or the mongo specific printjson() function which returns formatted JSON.

    To print all items in a result cursor in mongo shell scripts, use the following idiom:

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

Scripting

From the system prompt, use mongo to evaluate JavaScript.

--eval option

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

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

This returns the output of db.getCollectionNames() using the mongo shell connected to the mongod or mongos instance running on port 27017 on the localhost interface.

Execute a JavaScript file

You can specify a .js file to the mongo shell, and mongo will execute the JavaScript directly. Consider the following example:

mongo localhost:27017/test myjsfile.js

This operation executes the myjsfile.js script in a mongo shell that connects to the test database on the mongod instance accessible via the localhost interface on port 27017.

Alternately, you can specify the mongodb connection parameters inside of the javascript file using the Mongo() constructor. See Opening New Connections for more information.

You can execute a .js file from within the mongo shell, using the load() function, as in the following:

load("myjstest.js")

This function loads and executes the myjstest.js file.

The load() method accepts relative and absolute paths. If the current working directory of the mongo shell is /data/db, and the myjstest.js resides in the /data/db/scripts directory, then the following calls within the mongo shell would be equivalent:

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

NOTE: 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.

MongoDB - The mongo Shell, Write Scripts for the mongo Shell的更多相关文章

  1. 3.Write Scripts for the mongo Shell-官方文档摘录

    总结 1 使用js进行获取数据的方法 2 js方式和原生mongo shell的交互方式的区别写法 3 需要将所有数据打印出来使用到的循环示例 cursor = db.collection.find( ...

  2. Mongo DB Study: first face with mongo DB

    Mongo DB Study: first face with mongo DB 1.  study methods: 1.  Translate: I am the mongo DB organiz ...

  3. linux shell 的前世今生和流行BASH SHELL的特点

    前言 shell作为用户和操作系统内核交互的接口,也不断的在发展迭代.shell的发展也离不开unix/linux 系统的发展.并且在开源社区对shell的发展也起到了推动作用. 内容思维导图简介 发 ...

  4. shell 学习笔记1-什么是shell,shell变量

    一.介绍 1.什么是shell Shell 既是一种命令语言,又是一种程序设计语言,他在操作系统得最外层,负责直接与用户对话,把用户得输入解释个OS,并处理各类操作系统得输出结果,输出到屏幕返回个i用 ...

  5. ipython, 一个 python 的交互式 shell,比默认的python shell 好用得多,支持变量自动补全,自动缩进,支持 bash shell 命令,内置了许多很有用的功能和函数

    一个 python 的交互式 shell,比默认的python shell 好用得多,支持变量自动补全,自动缩进,支持 bash shell 命令,内置了许多很有用的功能和函数. 若用的是fish s ...

  6. Linux Shell 之 我的第一个Shell程序

      这里我首先会介绍一个Shell是什么,再介绍我的第一个Shell程序和从中总结的经验. 一.Shell是什么 在说我的这个Shell程序之前,还是先跟大家说说什么是Shell吧,相信Shell这个 ...

  7. shell脚本中执行另一个shell脚本

    分类: 可以在一个shell脚本中执行另一个shell脚本(或非可执行文件,主要用于取得一些变量的值),方法是: . 文件名(包括路径) 或 变量=文件名(包括路径) . $变量   注意,圆点后面有 ...

  8. Shell 脚本中调用另一个 Shell 脚本的三种方式

    主要以下有几种方式: Command Explanation fork 新开一个子 Shell 执行,子 Shell 可以从父 Shell 继承环境变量,但是子 Shell 中的环境变量不会带回给父 ...

  9. 子shell以及什么时候进入子shell

    bash&shell系列文章:http://www.cnblogs.com/f-ck-need-u/p/7048359.html 子shell的概念贯穿整个shell,写shell脚本时更是不 ...

随机推荐

  1. 让AllocateHwnd接受一般函数地址作参数

    http://www.xuebuyuan.com/1889769.html Classes单元的AllocateHWnd函数是需要传入一个处理消息的类的方法的作为参数的,原型: function Al ...

  2. CORTEX -M3 : Registers in depth

    http://www.zembedded.com/cortex-m3-registers-in-depth/ Thanks for the overwhelm response you show in ...

  3. Python 数据类型

    数据类型计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种各样的数据,不同的数据,需要定义 ...

  4. [连载]JavaScript讲义(05)--- 数据处理

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamFja2ZydWVk/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA ...

  5. Javascript加载执行问题探索

    转自:http://www.cnblogs.com/huangxincheng/archive/2011/12/04/2275988.html 前言 最近研究MongoDB数据库,无意间发现的好博客, ...

  6. java课堂练习之可变參数与卫条件

    /*  有人邀请A,B,C,D,E,F 6个人參加一项会议,这6个人有些奇怪.由于他们有非常多要求,已知:  1)A,B两人至少有1人參加会议:  2)A,E,F 3人中有2人參加会议.  3)B和C ...

  7. 制作简易计算器处理结果Servlet

    ResultServlet.java: package com.you.servlet; import java.io.IOException; import java.io.PrintWriter; ...

  8. ACM-最短路(SPFA,Dijkstra,Floyd)之最短路——hdu2544

    ***************************************转载请注明出处:http://blog.csdn.net/lttree************************** ...

  9. 基于Ascensor.js全屏切换页面插件

    今天给大家分享一款基于Ascensor.js全屏切换页面插件,这款实例 适用浏览器:IE8.360.FireFox.Chrome.Safari.Opera.傲游.搜狗.世界之窗.效果图如下: 在线预览 ...

  10. Linux 混杂设备、外部中断和输入子系统

    混杂设备也是一种字符设备,主设备号固定为10.相对于普通字符设备驱动,它不需要自己去生成设备文件. 1.声明使用的头文件 #include <linux/miscdevice.h> 2.定 ...