Mongodb-the MONGO Shell, Write Scripts for the MONGO shell

Source: Internet
Author: User
Tags mongo shell

You can write scripts for theMONGOShell in JavaScript this manipulate data in MongoDB or perform administrative Operation. For more information about theMONGOShell, see the Running. js files via a MONGO shell Instance on the Server SE Ction For more information about using theseMONGOscript.

This tutorial provides a introduction to writing JavaScript, the usesShell to access MongoDB.

Opening New Connections

From theMONGOshell or from a JavaScript file, you can instantiate database connections using theMONGO () 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 DEFA Ult port and sets the globalDBvariable tomyDatabaseusing thegetdb ()method:

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

If connecting to a MongoDB instance this enforces access control, you can use theDb.auth ()method to Authenticat E.

Additionally, you can use theConnect ()method to connect to the MongoDB instance. The following example connects to the MongoDB instance that's running onlocalhostwith the Non-default port27020and set the globalDBvariable:

> db = Connect ("Localhost:27020/mydatabase");

See ALSO: MONGO Shell Methods

Differences between Interactive and scriptedMONGO

When writing scripts for theMONGOShell, consider the following:

To set theDBglobal variable, use thegetdb ()method or theconnect ()method. You can assign the database reference to a variable and other thandb.

Write operations in theMONGOshell with a write concern of {w:1} by default. If performing bulk operations, use theBulk ()methods. See Write Method acknowledgements for more information.

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

Cannot use any shell helper (e.g. use <dbname>, show dbs, etc) inside the JavaScript file bec Ause They is not valid JavaScript.

The following table maps the most commonMONGOshell 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 ': ' * '})
cursor = Db.collection.find ()
if (Cursor.hasnext ()) { ();

In interactive mode,MONGOprints the results of operations including the content of all cursors. In scripts, either use the JavaScriptprint ()function or theMONGOspecificPrintjson ()functi On which returns formatted JSON.
To print all items with a result cursor inMONGOshell scripts, use the following idiom:

cursor = Db.collection.find (); while (Cursor.hasnext ()) {    Printjson ( ());}


From the system prompt, useMONGOto evaluate JavaScript.


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

MONGO Test--eval "Printjson (Db.getcollectionnames ())"

This returns the output ofdb.getcollectionnames ()using theMONGOShell connected to theMONGOD orMONGOsinstance running on port27017on thelocalhostinterface.

Execute a JavaScript file

You can specify a. jsfile to theMONGOshell, andMONGO'll execute the JavaScript directly. Consider the following example:

MONGO Localhost:27017/test Myjsfile.js

This operation executes, themyjsfile.jsscript in aMONGOshell, connects to thetestD Atabase on theMongodinstance accessible via thelocalhostinterface on port27017.

Alternately, you can specify the MongoDB connection parameters inside of the JavaScript file using theMongo ()Constructor. See Opening New Connections for more information.

You can execute a. jsfile from within theMONGOShell, using theload ()function, as in the FO Llowing:

Load ("Myjstest.js")

This function loads and executes themyjstest.jsfile.

Theload ()method accepts relative and absolute paths. If the current working directory of theMONGOShell was/data/db, and themyjstest.jsresides in The/data/db/scriptsdirectory, then the following calls within theMONGOShell would is 

Load ("Scripts/myjstest.js") Load ("/data/db/scripts/myjstest.

Note: There is no search path for theload ()function. If the desired script is not in the current working directory or the full specified path,MONGOwon't be able To access the file.

Mongodb-the MONGO Shell, Write Scripts for the MONGO shell

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.