From 556eb246b2661cb4c841b41e1e78be50136f84f5 Mon Sep 17 00:00:00 2001 From: kay Date: Thu, 20 Dec 2012 02:56:23 -0500 Subject: [PATCH 1/4] DOCS-689 the mongo shell pages --- source/core/object-id.txt | 2 +- source/core/read-operations.txt | 5 +- source/mongo.txt | 701 +++++++++++++++++- source/reference.txt | 2 + source/reference/javascript.txt | 2 + .../mongo-shell-keyboard-shortcuts.txt | 142 ++++ source/reference/mongo-shell-reference.txt | 478 ++++++++++++ source/reference/mongo.txt | 33 +- 8 files changed, 1340 insertions(+), 25 deletions(-) create mode 100644 source/reference/mongo-shell-keyboard-shortcuts.txt create mode 100644 source/reference/mongo-shell-reference.txt diff --git a/source/core/object-id.txt b/source/core/object-id.txt index a5cac1b49e7..9e659826c52 100644 --- a/source/core/object-id.txt +++ b/source/core/object-id.txt @@ -150,6 +150,6 @@ Consider the following uses ``ObjectId()`` class in the This operation will return the following output: - .. code-block:: javascript + .. code-block:: none 507f191e810c19729de860ea diff --git a/source/core/read-operations.txt b/source/core/read-operations.txt index 38c3b802e06..9c955784ed6 100644 --- a/source/core/read-operations.txt +++ b/source/core/read-operations.txt @@ -702,7 +702,7 @@ variable: print(tojson(myItem)); } - As an alternative print operation, cosider the the ``printjson()`` + As an alternative print operation, consider the the ``printjson()`` helper method to replace ``print(tojson())``: .. code-block:: javascript @@ -727,7 +727,8 @@ See :ref:`JavaScript cursor methods ` and your information on cursor methods. .. [#set-shell-batch-size] You can use the ``DBQuery.shellBatchSize`` to - change the number of iteration from the default value ``20``. + change the number of iteration from the default value ``20``. See + :ref:`mongo-shell-executing-queries` for more information. Iterator Index ~~~~~~~~~~~~~~ diff --git a/source/mongo.txt b/source/mongo.txt index 678c21b152f..c73ccb24e5e 100644 --- a/source/mongo.txt +++ b/source/mongo.txt @@ -1,19 +1,692 @@ -======================= -Using the MongoDB Shell -======================= +========================= +Using the ``mongo`` Shell +========================= .. default-domain:: mongodb -.. seealso:: The introductory ":wiki:`Tutorial`" in the MongoDB wiki - and the ":wiki:`Mongo Shell `" wiki - pages for more information on the :program:`mongo` shell. +:program:`mongo` shell is the MongoDB interactive shell and is part of +the `MongoDB distribution `_. The +:program:`mongo` is located in the ``/bin`` +directory. -Consider the following reference material that addresses the -:program:`mongo` shell and its interface: +The :program:`mongo` shell is a JavaScript shell [#spider-monkey]_ from +which you can run queries and commands, perform database administrative +operations, and execute JavaScript code. -- :doc:`reference/mongo` -- :doc:`reference/javascript` -- :doc:`reference/operators` -- :doc:`reference/commands` -- :doc:`reference/aggregation` -- :doc:`reference/meta-query-operators` +This document provides an overview of using the :program:`mongo` shell. + +.. seealso:: + + - :doc:`/reference/mongo-shell-reference` for a reference guide of some of + the shell features. + + - :doc:`/tutorial/getting-started` tutorial to get started. + +.. [#spider-monkey] The :program:`mongo` shell is an extended + `Spider Monkey shell + `_ + +Start the ``mongo`` Shell +------------------------- + +To start the :program:`mongo` shell and connect to your :doc:`MongoDB +` instance running on **localhost** with **default port**: + +#. Go to your ````: + + .. code-block:: sh + + cd + +#. Type ``./bin/mongo`` to start :program:`mongo`: + + .. code-block:: sh + + ./bin/mongo + + If you have added the ``/bin`` to the + ``PATH`` environment variable, you can just type ``mongo`` instead + of ``./bin/mongo``. + +#. To display the database you are using, type ``db``: + + .. code-block:: sh + + db + + The command should return ``test``, which is the default database. + To switch databases, issue the ``use `` command, as in the + following example: + + .. code-block:: javascript + + use myDatabase + + See :ref:`mongo-shell-help-db` to list the available databases. See also + :ref:`mongo-shell-getSiblingDB` to access a different + database from the current database. + +To start the :program:`mongo` shell with other options, see +:ref:`examples of starting up mongo ` and +:doc:`mongo reference ` which provides details on the +available options. + +.. note:: + + During startup, :program:`mongo` checks the user's :envvar:`HOME` + directory for a JavaScript file named :ref:`.mongorc.js + `. If this file is found, its contents are + interpreted and run by the shell prior to displaying the prompt for + the first time. If a JavaScript file or expression is specified to + be executed by the shell, such as with :option:`mongo --eval + \ ` or :option:`mongo \ + <>`, :program:`mongo` reads the :ref:`.mongorc.js + ` file *after* the JavaScript has finished + processing. + +.. _mongo-shell-executing-queries: + +Executing Queries +----------------- + +From the :program:`mongo` shell, you can use the :doc:`shell methods +` to run queries, such as the following example: + +.. code-block:: javascript + + db.myCollection.find() + +- The ``db`` is a variable that refers to the current database. + +- The ``myCollection`` is the name of the collection to query. See + :ref:`mongo-shell-help-collection` to list the available collections. + + If the :program:`mongo` shell does not accept the name of the + collection, for instance if the name contains a space or starts with + a number, use an alternate syntax to refer to the collection, as in + the following: + + .. code-block:: javascript + + db['3test'].find() + +- The :method:`find() ` method is the JavaScript + method to retrieve documents from ``myCollection``. The + :method:`find() ` method returns a + :term:`cursor` to the results; however, in the :program:`mongo` + shell, if the returned cursor is not assigned to a variable, then the + cursor is automatically iterated up to 20 times to print up to the + first 20 documents that match the query. The :program:`mongo` shell + will prompt ``Type it`` to iterate another 20 times. + + You can use the ``DBQuery.shellBatchSize`` to change the number of + iteration from the default value ``20``, as in the following example + which sets it to ``10``: + + .. code-block:: javascript + + DBQuery.shellBatchSize = 10; + + For more information and examples on cursor handling in the + :program:`mongo` shell, see :ref:`read-operations-cursors`. + + See also :ref:`mongo-shell-help-cursor` for list of + cursor help in the in the :program:`mongo` shell. + +For more information on performing basic operations in the shell, see: + +- :doc:`/reference/mongo-shell-reference` + +- :doc:`/applications/create` + +- :doc:`/applications/read` + +- :doc:`/applications/update` + +- :doc:`/applications/delete` + +- :doc:`/administration/indexes` + +- :doc:`/core/read-operations` + +- :doc:`/core/write-operations` + +.. _mongo-shell-print: + +Print +----- + +The :program:`mongo` shell automatically prints the results of the +:method:`find() ` method if the returned cursor +is not assigned to a variable. To format the result as :term:`JSON`, you can +add the ``.pretty()`` to the operation, as in the following: + +.. code-block:: javascript + + db.myCollection.find().pretty() + +In addition, you can use the following explicit print methods in the +:program:`mongo` shell: + +- ``print()`` to print without formatting + +- ``print(tojson())`` to print with :term:`JSON` formatting and equivalent to ``printjson()`` + +- ``printjson()`` to print with :term:`JSON` formatting and equivalent + to ``print(tojson())`` + +.. _mongo-shell-exit: + +Exit the Shell +-------------- + +To exit the shell, type ``quit()`` or use the ```` shortcut. + +.. _mongo-shell-data-type: + +Data Types +---------- + +Date +~~~~ + +The :program:`mongo` shell provides various options to return the date, +either as a string or as an object: + +- ``Date()`` method which returns the current date as a string + +- ``Date()`` constructor which returns an ``ISODate`` object when used + with the ``new`` operator. + +- ``ISODate()`` constructor which returns an ``ISODate`` object when + used with *or* without the ``new`` operator. + +Consider the following examples: + +- To get the date as a string, use the ``Date()`` method, as in the + following example: + + .. code-block:: javascript + + var myDateString = Date(); + + - To print the value of the variable, type the variable name in the + shell, as in the following: + + .. code-block:: javascript + + myDateString + + The result is the value of ``myDateString``: + + .. code-block:: javascript + + Wed Dec 19 2012 01:03:25 GMT-0500 (EST) + + - To verify the type, use the ``typeof`` operator, as in the + following: + + .. code-block:: javascript + + typeof myDateString + + The operation returns ``string``. + +- To get the date as an ``ISODate`` object, instantiate a new instance + using the ``Date()`` constructor with the ``new`` operator, as in the + following example: + + .. code-block:: javascript + + var myDateObject = new Date(); + + - To print the value of the variable, type the variable name in the + shell, as in the following: + + .. code-block:: javascript + + myDateObject + + The result is the value of ``myDateObject``: + + .. code-block:: javascript + + ISODate("2012-12-19T06:01:17.171Z") + + - To verify the type, use the ``typeof`` operator, as in the + following: + + .. code-block:: javascript + + typeof myDateObject + + The operation returns ``object``. + +- To get the date as an ``ISODate`` object, instantiate a new instance + using the ``ISODate()`` constructor *without* the ``new`` operator, + as in the following example: + + .. code-block:: javascript + + var myDateObject2 = ISODate(); + + You can use the ``new`` operator with the ``ISODate()`` constructor + as well. + + - To print the value of the variable, type the variable name in the + shell, as in the following: + + .. code-block:: javascript + + myDateObject2 + + The result is the value of ``myDateObject2``: + + .. code-block:: javascript + + ISODate("2012-12-19T06:15:33.035Z") + + - To verify the type, use the ``typeof`` operator, as in the + following: + + .. code-block:: javascript + + typeof myDateObject2 + + The operation returns ``object``. + +ObjectId +~~~~~~~~ + +The :program:`mongo` shell provides the :doc:`new ObjectId() +` wrapper class to generate a new :term:`ObjectId`. + +Type Help +~~~~~~~~~ + +To get a list of the wrapper classes available in the :program:`mongo` +shell, such as ``BinData()``, type ``help misc`` in the +:program:`mongo` shell: + +.. code-block:: javascript + + help misc + +.. _mongo-shell-help: + +Getting Help +------------ + +.. _mongo-shell-help-command-line: + +Command Line Help +~~~~~~~~~~~~~~~~~ + +To see the list of options and help for starting the :program:`mongo` +shell, use the :option:`--help ` option from the command line: + +.. code-block:: sh + + mongo --help + +Shell Help +~~~~~~~~~~ + +To see the list of help, in the :program:`mongo` shell, type ``help``: + +.. code-block:: javascript + + help + +.. _mongo-shell-help-db: + +Database Help +~~~~~~~~~~~~~ + +- To see the list of databases on the server, use the ``show dbs`` + command: + + .. code-block:: javascript + + show dbs + +- To see the list of help for database methods, use the ``db.help()`` command: + + .. code-block:: javascript + + db.help() + +- To see the database method implementation, type the ``db.`` without the parenthesis (``()``), as in the following example + which will return the implementation of the method ``addUser()``: + + .. code-block:: javascript + + db.addUser + +.. _mongo-shell-help-collection: + +Collection Help +~~~~~~~~~~~~~~~ + +- To see the list of collections in the current database, use the + ``show collections`` command: + + .. code-block:: javascript + + show collections + +- To see the list of help for collection methods, use the + ``db..help()`` command: + + .. code-block:: javascript + + db.collection.help() + + The ```` can be the name of an existing collection or a + non-existing collection. + +- To see the collection method implementation, type the + ``db..`` name without the parenthesis (``()``), + as in the following example which will return the implementation of + the :method:`save() ` method: + + .. code-block:: javascript + + db.collection.save + +.. _mongo-shell-help-cursor: + +Cursor Help +~~~~~~~~~~~ + +When you perform :ref:`read operations ` with +the :method:`find() ` method in the +:program:`mongo` shell, you can use various cursor methods to modify +the :method:`find() ` behavior and various +JavaScript methods to handle the cursor returned from the +:method:`find() ` method. + +- To list the available modifier and cursor handling methods, use the + ``db.collection.find().help()`` command: + + .. code-block:: javascript + + db.collection.find().help() + + The ```` can be the name of an existing collection or a + non-existing collection. + +- To see the method implementation, type the + ``db..find().`` name without the parenthesis + (``()``), as in the following example which will return the + implementation of the ``toArray()`` method: + + .. code-block:: javascript + + db.collection.find().toArray + +.. _mongo-shell-tips: + +Tips +---- + +Working from the Prompt +~~~~~~~~~~~~~~~~~~~~~~~ + +Line Continuation Mode +`````````````````````` + +If you end a line with an open parenthesis (``'('``), an open brace +(``'{'``), or an open bracket (``'['``), then the following lines start +with ellipsis (``"..."``) until the you enter the corresponding closing +parenthesis (``')'``), the closing brace (``'}'``) or the closing +bracket (``']'``). The :program:`mongo` shell waits for the closing +parenthesis, closing brace, or the closing bracket before evaluating +the code, as in the following example: + +.. code-block:: javascript + + > if ( x > 0 ) { + ... count++; + ... print (x); + ... } + +You can break out of the line continuation mode if you enter two blank +lines, as in the following example: + +.. code-block:: javascript + + > if (x > 0 + ... + ... + > + +.. _mongo-shell-getSiblingDB: + +Temporary Access to a Different Database +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can use :method:`db.getSiblingDB()` method to access another +database without switching databases, as in the following example which +first switches to the ``test`` database and then accesses the +``sampleDB`` database from the ``test`` database: + +.. code-block:: javascript + + use test + + db.getSiblingDB('sampleDB').getCollectionNames(); + +.. _mongo-shell-keyboard-shortcuts: + +Keyboard Shortcuts +~~~~~~~~~~~~~~~~~~ + +The :program:`mongo` shell supports keyboard shortcuts. For example, + +- Use the up/down arrow keys to scroll through command history. See + :ref:`.dbshell.js ` documentation for more + information on the ``.dbshell.js`` file. + +- Use ```` to autocomplete or to list the completion + possibilities, as in the following example which uses ```` to + complete the method name starting with the letter ``'c'``: + + .. code-block:: javascript + + db.myCollection.c + + Because there are many collection methods starting with the letter + ``'c'``, the ```` will list the various methods that start with + ``'c'``. + +For a full list of the shortcuts, see +:doc:`/reference/mongo-shell-keyboard-shortcuts`. + +Customize ``mongo`` Shell Prompt +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.9 + +You can change the :program:`mongo` shell prompt by setting the +``prompt`` variable. This allows for additional information to be +displayed in the prompt. + +The ``prompt`` variable can be set to any arbitrary JavaScript code, +including a function that returns a string. Consider the following +examples: + +- Set the shell prompt to display the hostname and the database issued: + + .. code-block:: javascript + + var host = db.serverStatus().host; + var prompt = function() { return db+"@"+host+"> "; } + + The :program:`mongo` shell prompt should now reflect the new prompt: + + .. code-block:: none + + test@my-machine.local> + +- Set the shell prompt to display the database statistics: + + .. code-block:: javascript + + var prompt = function() { + return "Uptime:"+db.serverStatus().uptime+" Files:"+db.stats().objects+" > "; + } + + The :program:`mongo` shell prompt should now reflect the new prompt: + + .. code-block:: none + + Uptime:1052 Files:25024787 > + +You can add the logic for the prompt in the :ref:`.mongorc.js +` file to set the prompt each time you start up the +:program:`mongo` shell. + +Using Editors +~~~~~~~~~~~~~ + +.. versionaddedd: 2.1 + +You can use your own editor in the :program:`mongo` shell by setting +the :envvar:`EDITOR` environment variable before starting the +:program:`mongo` shell. Once in the :program:`mongo` shell, you can +edit with the specified editor by typing ``edit `` or ``edit +``, as in the following example: + +#. Set the :envvar:`EDITOR` variable from the command line prompt: + + .. code-block:: javascript + + EDITOR=vim + +#. Start the :program:`mongo` shell: + + .. code-block:: sh + + mongo + +#. Define a function ``myFunction``: + + .. code-block:: javascript + + function myFunction () { } + +#. Edit the function using your editor: + + .. code-block:: javascript + + edit myFunction + + The command should open the ``vim`` edit session. Remember to save + your changes. + +#. Type ``myFunction`` to see the function definition: + + .. code-block:: javascript + + myFunction + + The result should be the changes from your saved edit: + + .. code-block:: javascript + + function myFunction() { + print("This was edited"); + } + +.. _mongo-shell-new-connections: + +Opening New Connections +----------------------- + +From the :program:`mongo` shell or from a JavaScript file, you can +instantiate database connections using the ``Mongo()`` constructor: + +.. code-block:: javascript + + new Mongo() + new Mongo() + new Mongo() + +Consider the following example that instantiates a new connection to +the MongoDB instance running on localhost on the default port and set +the current ``db`` to ``myDatabase``: + +.. code-block:: javascript + + conn = new Mongo(); + db = conn.getDB("myDatabase"); + +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 +``207020`` and set the current ``db``: + +.. code-block:: javascript + + db = connect("localhost:27020/myDatabase"); + +If you create new connections inside a :ref:`JavaScript file +`, you must specify the ``db`` variable in +the specified methods. You **cannot** use ``use `` inside the +file. Additionally, inside the script, you would need to call +:method:`db.getLastErrorObj()` or :method:`db.getLastError()` +explicitly to wait for the result of :doc:`write +operations`. + +.. _mongo-shell-scripting: + +Scripting +--------- + +From the command line, use :program:`mongo` to evaluate JavaScript. + +``--eval`` option +~~~~~~~~~~~~~~~~~ + +Use :option:`mongo \ --eval "\" ` +to evaluate JavaScript code snippet, as in the following: + +.. code-block:: sh + + mongo test --eval "printjson(db.getCollectionNames())" + +.. _mongo-shell-javascript-file: + +Pass a JavaScript file +~~~~~~~~~~~~~~~~~~~~~~ + +Use :ref:`mongo \ \ ` as in the following: + +.. code-block:: sh + + mongo localhost:27017/test myJSFile.js + +You can also specify the connection information inside the JavaScript +file using the ``Mongo()`` constructor. See +:ref:`mongo-shell-new-connections` for more information. + +.. wiki content -- I don't think the following applies anymore + Numbers + By default, the shell treats all numbers as floating-point values. + You have the option to work with 64-bit integers by using a class + built into the shell called NumberLong() If you have long/integer + BSON data from the database you may see something like this: + {"count" : NumberLong("575175")} + Setting/incrementing any number from javascript will (most likely) + change the data type to a floating point value. + Here is an example of creating a document with a long field: + doc = { field: new NumberLong("123212313")} + Note that prior to 1.6 long numbers might be displayed like this: + "bytes" : { + "floatApprox" : 5284376243087482000, + "top" : 1230364721, + "bottom" : 4240317554 + } + \ No newline at end of file diff --git a/source/reference.txt b/source/reference.txt index e17cf6fa1e4..ff95a62bd19 100644 --- a/source/reference.txt +++ b/source/reference.txt @@ -94,6 +94,8 @@ General Reference reference/limits reference/mongodb-extended-json + reference/mongo-shell-reference + reference/mongo-shell-keyboard-shortcuts reference/glossary .. seealso:: The :ref:`genindex` may provide useful insight into the diff --git a/source/reference/javascript.txt b/source/reference/javascript.txt index 347e11a6dc0..170fd5a8021 100644 --- a/source/reference/javascript.txt +++ b/source/reference/javascript.txt @@ -96,6 +96,8 @@ Data Aggregation Methods Administrative Functions ------------------------ +.. _js-administrative-methods: + Database Methods ~~~~~~~~~~~~~~~~ diff --git a/source/reference/mongo-shell-keyboard-shortcuts.txt b/source/reference/mongo-shell-keyboard-shortcuts.txt new file mode 100644 index 00000000000..fea906f32cc --- /dev/null +++ b/source/reference/mongo-shell-keyboard-shortcuts.txt @@ -0,0 +1,142 @@ +================================== +``mongo`` Shell Keyboard Shortcuts +================================== + +.. default-domain:: mongodb + +The :program:`mongo` shell supports the following keyboard shortcuts +[#multiple-bindings]_: + +.. list-table:: + + * - Up arrow + - Retrieve previous command from history + + * - Down-arrow + - Retrieve next command from history + + * - Home + - Go to beginning of the line + + * - End + - Go to end of the line + + * - Tab + - Autocomplete method/command + + * - Left-arrow + - Go backward one character + + * - Right-arrow + - Go forward one character + + * - Ctrl-left-arrow + - Go backward one word + + * - Ctrl-right-arrow + - Go forward one word + + * - Meta-left-arrow + - Go backward one word + + * - Meta-right-arrow + - Go forward one word + + * - Ctrl-A + - Go to the beginning of the line + + * - Ctrl-B + - Go backward one character + + * - Ctrl-C + - Exit the :program:`mongo` shell + + * - Ctrl-D + - Delete a char (or exit the :program:`mongo` shell) + + * - Ctrl-E + - Go to the end of the line + + * - Ctrl-F + - Go forward one character + + * - Ctrl-G + - Abort + + * - Ctrl-J + - Accept/evaluate the line + + * - Ctrl-K + - Kill/erase the line + + * - Ctrl-L or type ``cls`` + - Clear the screen + + * - Ctrl-M + - Accept/evaluate the line + + * - Ctrl-N + - Retrieve next command from history + + * - Ctrl-P + - Retrieve previous command from history + + * - Ctrl-R + - Reverse-search command history + + * - Ctrl-S + - Forward-search command history + + * - Ctrl-T + - Transpose characters + + * - Ctrl-U + - Perform Unix line-discard + + * - Ctrl-W + - Perform Unix word-rubout + + * - Ctrl-Y + - Yank + + * - Ctrl-Z + - Suspend (job control works in linux) + + * - Ctrl-H + - Backward-delete a character + + * - Ctrl-I + - Complete, same as Tab + + * - Meta-B + - Go backward one word + + * - Meta-C + - Capitalize word + + * - Meta-D + - Kill word + + * - Meta-F + - Go forward one word + + * - Meta-L + - Change word to lowercase + + * - Meta-U + - Change word to uppercase + + * - Meta-Y + - Yank-pop + + * - Meta-Backspace + - Backward-kill word + + * - Meta-< + - Retrieve the first command in command history + + * - Meta-> + - Retrieve the last command in command history + +.. [#multiple-bindings] MongoDB accommodates multiple keybinding. + Starting version 1.9, you can use some basic emacs keystrokes. diff --git a/source/reference/mongo-shell-reference.txt b/source/reference/mongo-shell-reference.txt new file mode 100644 index 00000000000..d210d78140e --- /dev/null +++ b/source/reference/mongo-shell-reference.txt @@ -0,0 +1,478 @@ +========================= +``mongo`` Shell Reference +========================= + +.. default-domain:: mongodb + +``mongo`` Shell Command History +------------------------------- + +You can retrieve previous commands issued in the :program:`mongo` shell +with the up and down arrow keys. Command history is stored in +``~/.dbshell`` file. See :ref:`.dbshell ` for more +information. + +Command Line Options +-------------------- + +The :program:`mongo` executable can be started with numerous options. +See :doc:`mongo executable ` page for details on all +available options. + +The following table displays some common options for :program:`mongo`: + +.. list-table:: + :header-rows: 1 + + * - Option + + - Description + + * - :option:`--help ` + + - Show command line options + + * - :option:`--nodb ` + + - Start :program:`mongo` shell without connecting to a database. + + To connect later, see :ref:`mongo-shell-new-connections`. + + * - :option:`--shell ` + + - Used in conjunction with a JavaScript file (i.e. + :ref:`\ `) to continue in the + :program:`mongo` shell after running the JavaScript file. + + See :ref:`JavaScript file ` for an + example. + +Command Helpers +--------------- + +The :program:`mongo` shell provides various help. The following table +displays some common help methods and commands: + +.. list-table:: + :header-rows: 1 + + * - Help Methods and Commands + + - Description + + * - ``help`` + + - Show help. + + * - ``db.help()`` + + - Show help for database methods. + + * - ``db..help()`` + + - Show help on collection methods. The ```` can be the + name of an existing collection or a non-existing collection. + + * - ``show dbs`` + + - Print a list of all databases on the server. + + * - ``use `` + + - Switch current database to ````. The :program:`mongo` shell + variable ``db`` is set to the current database. + + * - ``show collections`` + + - Print a list of all collections for current database + + * - ``show users`` + + - Print a list of users for current database. + + * - ``show profile`` + + - Print the five most recent operations that took 1 millisecond or + more. See documentation on the :doc:`database profiler + ` for more information. + +Basic Shell Javascript Operations +---------------------------------- + +The :program:`mongo` shell provides numerous +:doc:`/reference/javascript` for database operations. + +In the :program:`mongo` shell, ``db`` is the variable that references +the current database. The variable is automatically set to the default +database ``test`` or is set when you use the ``use `` to switch +current database. + +The following table displays some common JavaScript operations: + +.. list-table:: + :header-rows: 1 + + * - JavaScript Database Operations + + - Description + + * - :method:`db.auth()` + + - If running in secure mode, authenticate the user. + + * - ``coll = db.`` + + - Set a specific collection in the current database to a variable + ``coll``, as in the following example: + + .. code-block:: javascript + + coll = db.myCollection; + + You can perform operations on the ``myCollection`` using the + variable, as in the following example: + + .. code-block:: javascript + + coll.find(); + + * - :method:`db.collection.find()` + + - Find all documents in the collection and returns a cursor. + + See the :doc:`/applications/read` and + :doc:`/core/read-operations` for more information and examples. + + See :ref:`read-operations-cursors` for additional information on + cursor handling in the :program:`mongo` shell. + + * - :method:`db.collection.insert()` + + - Insert a new document into the collection. + + * - :method:`db.collection.update()` + + - Update an existing document in the collection. + + See :doc:`/applications/update` for more information. + + * - :method:`db.collection.save()` + + - Insert either a new document or update an existing document in + the collection. + + See :doc:`/applications/update` for more information. + + * - :method:`db.collection.remove()` + + - Delete documents from the collection. + + See :doc:`/applications/delete` for more information. + + * - :method:`db.collection.drop()` + + - Drops or removes completely the collection. + + * - :method:`db.collection.ensureIndex()` + + - Create a new index on the collection if the index does not + exist; otherwise, the operation has no effect. + + * - :method:`db.getSiblingDB()` or ``db.getSisterDB()`` + + - Return a reference to another database using this same + connection without explicitly switching the current database. + This allows for cross database queries. See + :ref:`mongo-shell-getSiblingDB` for more information. + +For more information on performing operations in the shell, see: + +- :doc:`/applications/create` + +- :doc:`/applications/read` + +- :doc:`/applications/update` + +- :doc:`/applications/delete` + +- :doc:`/administration/indexes` + +- :doc:`/core/read-operations` + +- :doc:`/core/write-operations` + +- :doc:`/reference/javascript` + +Queries +------- + +In the :program:`mongo` shell, read operations are performed using +:method:`db.collection.find()` and :method:`db.collection.findOne()`. + +The :method:`db.collection.find()` method returns a cursor which the +:program:`mongo` shell iterates to print on screen. By default, the +first 20 results are printed. The :program:`mongo` shell will prompt +the user to ``Type it`` to continue iterating the next 20 results. + +The following table provides some common read operations in the +:program:`mongo` shell: + +.. list-table:: + :header-rows: 1 + + * - Read Operations + + - Description + + * - :method:`db.collection.find(\) ` + + - Find the documents matching the ```` criteria in the + collection. If the ```` criteria is not specified or is + empty (i.e ``{}`` ), the read operation selects all documents in + the collection. + + The following example selects the documents in the ``users`` + collection with the ``name`` field equal to ``"Joe"``: + + .. code-block:: javascript + + coll = db.users; + coll.find( { name: "Joe" } ); + + For more information on specifying the ```` criteria, see + :ref:`read-operations-query-argument`. + + * - :method:`db.collection.find( \, \ ) + ` + + - Find documents matching the ```` criteria and return just + specific fields in the ````. + + The following example selects all documents from the collection + but returns only the ``name`` field and the ``_id`` field. The + ``_id`` is always returned unless explicitly specified to not + return. + + .. code-block:: javascript + + coll = db.users; + coll.find( { }, + { name: true } + ); + + For more information on specifying the ````, see + :ref:`read-operations-projection`. + + * - :method:`db.collection.find().sort( \ ) ` + + - Return results in the specified ````. + + The following example selects all documents from the collection + and returns the results sorted by the ``name`` field in + ascending order (``1``). Use ``-1`` for descending order: + + .. code-block:: javascript + + coll = db.users; + coll.find().sort( { name: 1 } ); + + * - :method:`db.collection.find( \ ).sort( \ ) + ` + + - Return the documents matching the ```` criteria in the + specified ````. + + * - :method:`db.collection.find( ... ).limit( \ ) ` + + - Limit result to `n` rows. Highly recommended if you need only + a certain number of rows for best performance. + + * - :method:`db.collection.find( ... ).skip( \ ) + ` + + - Skip n results. + + * - :method:`db.collection.count() ` + + - Returns total number of objects in the collection. + + * - :method:`db.collection.find( \ ).count() ` + + - Returns the total number of objects that match the query. + + The :method:`` ignores :method:`limit() + ` and :method:`skip() `. For + example, if 100 records match but the limit is 10, + :method:`count() ` will return 100. This will be + faster than iterating yourself, but still take time. + + * - :method:`db.collection.findOne( \ ) ` + + - Find and return a single object. Returns null if not found. + + The following example selects a single documents in the + ``users`` collection with the ``name`` field matches to + ``"Joe"``: + + .. code-block:: javascript + + coll = db.users; + coll.find( { name: "Joe" } ); + + Internally, the :method:`findOne() ` + method is the :method:`find() ` method + with a :method:`limit(1) `. + +See :doc:`/applications/read` and :doc:`/core/read-operations` +documentation for more information and examples. See +:doc:`/reference/operators` to specify other query operators. + +Error Checking Administrative Methods +------------------------------------- + +The :program:`mongo` shell provides numerous :ref:`administrative +database methods `, including error checking +methods. + +The following table lists some of the error checking administrative methods: + +.. list-table:: + :header-rows: 1 + + * - Error Checking Methods + + - Description + + * - :method:`db.getLastError()` + + - Returns error message from the last operation. + + * - :method:`db.getLastErrorObj()` + + - Returns the error object from the last operation. + + * - :method:`db.getPrevError()` + + - Returns error from previous operations. + + * - :method:`db.resetError()` + + - Clear error memory. + +Administrative Command Helpers +------------------------------ + +The following table lists some common general administrative methods: + +.. list-table:: + :header-rows: 1 + + * - JavaScript Database Administrative Methods + - Description + + * - :method:`db.cloneDatabase(\) ` + + - Clone the current database from the ``host`` specified. The + ``host`` database instance must be in noauth mode. + + * - :method:`db.copyDatabase(\, \, \) ` + + - Copy the ```` database from the ```` to the ```` + database on the current server. + + The ```` database instance must be in ``noauth`` mode. + + * - :method:`db.fromColl.renameCollection(\) + ` + + - Rename collection from fromColl to toColl. + + * - :method:`db.repairDatabase()` + + - Repair and compact the current database. This operation can be + very slow on large databases. + + * - :method:`db.addUser( \, \ ) ` + + - Add user to current database. + + * - :method:`db.getCollectionNames()` + + - Get the list of all collections in the current database. + + * - :method:`db.dropDatabase()` + + - Drops the current database. + +See also :ref:`administrative database methods +` for a full list of methods. + +Opening Additional Connections +------------------------------ + +You can create new connections within the :program:`mongo` shell. + +The following table displays the methods to create the connections: + +.. list-table:: + :header-rows: 1 + + * - JavaScript Connection Create Methods + + - Description + + * - ``db = connect(":/")`` + + - Open a new database connection. + + * - ``conn = new Mongo()`` + + ``db = conn.getDB("dbname")`` + + - Open a connection to a new server using ``new Mongo()``. + + Use ``getDB()`` method of the connection to select a database. + +See also :ref:`mongo-shell-new-connections` for more information on the +opening new connections from the :program:`mongo` shell. + +Miscellaneous +------------- + +The following table displays some miscellaneous method: + +.. list-table:: + :header-rows: 1 + + * - Method + + - Description + + * - ``Object.bsonsize()`` + + - Prints the :term:`BSON` size of an + +See the `MongoDB JavaScript API Documentation +`_ for a full list. + +Additional Resources +-------------------- + +Consider the following reference material that addresses the +:program:`mongo` shell and its interface: + +- :doc:`/reference/mongo` + +- :doc:`/reference/javascript` + +- :doc:`/reference/operators` + +- :doc:`/reference/commands` + +- :doc:`/reference/aggregation` + +- :doc:`/reference/meta-query-operators` + +Additionally, the MongoDB source code repository includes a `jstests +directory `_ +which contains numerous :program:`mongo` shell scripts. diff --git a/source/reference/mongo.txt b/source/reference/mongo.txt index c980d1f38af..a2b8214bb25 100644 --- a/source/reference/mongo.txt +++ b/source/reference/mongo.txt @@ -35,6 +35,8 @@ environment. This document addresses the basic invocation of the Interface --------- +.. _mongo-shell-options: + Options ~~~~~~~ @@ -51,7 +53,9 @@ Options .. option:: --nodb - Prevents the shell from connecting to any database instances. + Prevents the shell from connecting to any database instances. Later, + to connect to a database within the shell, see + :ref:`mongo-shell-new-connections`. .. option:: --norc @@ -143,7 +147,6 @@ Options mongo 10.8.8.10/test .. _mongo-shell-file: - .. option:: Specifies a JavaScript file to run and then exit. @@ -155,6 +158,8 @@ Options Files ~~~~~ +.. _mongo-dbshell-file: + :file:`~/.dbshell` :program:`mongo` maintains a history of commands in the :file:`.dbshell` @@ -172,12 +177,22 @@ Files save the `.dbshell` file in the :command:`mongo.exe` working directory. +.. _mongo-mongorc-file: + :file:`~/.mongorc.js` - :program:`mongo` will read `.mongorc.js` from the home directory - of the user invoking :program:`mongo`. + :program:`mongo` will read the ``.mongorc.js`` file from the home + directory of the user invoking :program:`mongo`. In the file, users + can define variables, customize the :program:`mongo` shell prompt, + or update information that they would like updated every time they + launch a shell. If a JavaScript file or expression is specified to + be executed by the shell, such as with :option:`mongo --eval + \ ` or :ref:`mongo \ + `, :program:`mongo` reads the ``.mongorc.js`` file + *after* the JavaScript has finished processing. + Specify the :option:`mongo --norc` option to disable - reading `.mongorc.js`. + reading ``.mongorc.js``. :file:`/tmp/mongo_edit{}.js` @@ -203,9 +218,9 @@ Environment .. envvar:: HOME - Specifies the path to the home directory where :program:`mongo` - :program:`mongo` will read the :file:`.mongorc.js` file and write - the :file:`.dbshell` file. + Specifies the path to the home directory where :program:`mongo` will + read the :file:`.mongorc.js` file and write the :file:`.dbshell` + file. .. envvar:: HOMEDRIVE @@ -219,6 +234,8 @@ Environment :program:`mongo` will read the :file:`.mongorc.js` file and write the :file:`.dbshell` file. +.. _mongo-usage-examples: + Use --- From a8f3805d2dd8a00df959b4bb815c7338df547273 Mon Sep 17 00:00:00 2001 From: kay Date: Thu, 20 Dec 2012 10:22:45 -0500 Subject: [PATCH 2/4] DOCS-689 the mongo shell pages --- source/reference/mongo-shell-reference.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/reference/mongo-shell-reference.txt b/source/reference/mongo-shell-reference.txt index d210d78140e..073a67765a4 100644 --- a/source/reference/mongo-shell-reference.txt +++ b/source/reference/mongo-shell-reference.txt @@ -317,7 +317,7 @@ The following table provides some common read operations in the .. code-block:: javascript coll = db.users; - coll.find( { name: "Joe" } ); + coll.findOne( { name: "Joe" } ); Internally, the :method:`findOne() ` method is the :method:`find() ` method From 2327ffcdaea7d6718e565f884cf67e0b5dbc0bb2 Mon Sep 17 00:00:00 2001 From: kay Date: Thu, 20 Dec 2012 16:48:39 -0500 Subject: [PATCH 3/4] DOCS-689 incorporate feedback from mike and ed --- source/core/object-id.txt | 6 +-- source/core/read-operations.txt | 2 +- source/mongo.txt | 46 +++++++++++++++------- source/reference/mongo-shell-reference.txt | 14 +++---- 4 files changed, 43 insertions(+), 25 deletions(-) diff --git a/source/core/object-id.txt b/source/core/object-id.txt index 9e659826c52..e9f908b0d0c 100644 --- a/source/core/object-id.txt +++ b/source/core/object-id.txt @@ -39,9 +39,9 @@ information on MongoDB's document orientation. ObjectId() ---------- -The :program:`mongo` shell provides the ``ObjectId()`` wrapper class -to generate can generate a new ObjectId, and to provide the following -helper attribute and methods: +The :program:`mongo` shell provides the ``ObjectId()`` wrapper class to +generate a new ObjectId, and to provide the following helper attribute +and methods: - ``str`` diff --git a/source/core/read-operations.txt b/source/core/read-operations.txt index 9c955784ed6..79a29cd41cc 100644 --- a/source/core/read-operations.txt +++ b/source/core/read-operations.txt @@ -702,7 +702,7 @@ variable: print(tojson(myItem)); } - As an alternative print operation, consider the the ``printjson()`` + As an alternative print operation, consider the ``printjson()`` helper method to replace ``print(tojson())``: .. code-block:: javascript diff --git a/source/mongo.txt b/source/mongo.txt index c73ccb24e5e..3c1afcb593e 100644 --- a/source/mongo.txt +++ b/source/mongo.txt @@ -4,9 +4,9 @@ Using the ``mongo`` Shell .. default-domain:: mongodb -:program:`mongo` shell is the MongoDB interactive shell and is part of +The :program:`mongo` shell is the MongoDB interactive shell and is part of the `MongoDB distribution `_. The -:program:`mongo` is located in the ``/bin`` +:program:`mongo` program is located in the ``/bin`` directory. The :program:`mongo` shell is a JavaScript shell [#spider-monkey]_ from @@ -62,9 +62,9 @@ To start the :program:`mongo` shell and connect to your :doc:`MongoDB use myDatabase - See :ref:`mongo-shell-help-db` to list the available databases. See also - :ref:`mongo-shell-getSiblingDB` to access a different - database from the current database. + To list the available database, use the command ``show dbs``. See + also :ref:`mongo-shell-getSiblingDB` to access a different database + from the current database. To start the :program:`mongo` shell with other options, see :ref:`examples of starting up mongo ` and @@ -103,12 +103,14 @@ From the :program:`mongo` shell, you can use the :doc:`shell methods If the :program:`mongo` shell does not accept the name of the collection, for instance if the name contains a space or starts with - a number, use an alternate syntax to refer to the collection, as in - the following: + a number, you can use an alternate syntax to refer to the + collection, as in the following alternates: .. code-block:: javascript - db['3test'].find() + db["3test"].find() + + db.getCollection("3test").find() - The :method:`find() ` method is the JavaScript method to retrieve documents from ``myCollection``. The @@ -119,9 +121,9 @@ From the :program:`mongo` shell, you can use the :doc:`shell methods first 20 documents that match the query. The :program:`mongo` shell will prompt ``Type it`` to iterate another 20 times. - You can use the ``DBQuery.shellBatchSize`` to change the number of - iteration from the default value ``20``, as in the following example - which sets it to ``10``: + You can use the ``DBQuery.shellBatchSize`` variable to change the + number of iteration from the default value ``20``, as in the + following example which sets it to ``10``: .. code-block:: javascript @@ -158,8 +160,8 @@ Print The :program:`mongo` shell automatically prints the results of the :method:`find() ` method if the returned cursor -is not assigned to a variable. To format the result as :term:`JSON`, you can -add the ``.pretty()`` to the operation, as in the following: +is not assigned to a variable. To format the result, you can add the +``.pretty()`` to the operation, as in the following: .. code-block:: javascript @@ -426,6 +428,22 @@ JavaScript methods to handle the cursor returned from the db.collection.find().toArray +Some useful methods for handling cursors are: + +- :method:`hasNext() ` which checks whether the + cursor has more documents to return. + +- :method:`next() ` which returns the next document and + moves by one the position of the cursor. + +- :method:`forEach(\) ` which iterates the + whole cursor and applies the ```` to each document returned + by the cursor. + +For examples on iterating a cursor and retrieving the documents from +the cursor, see :ref:`cursor handling `. See +also :ref:`js-query-cursor-methods` for all available cursor methods. + .. _mongo-shell-tips: Tips @@ -615,7 +633,7 @@ instantiate database connections using the ``Mongo()`` constructor: new Mongo() Consider the following example that instantiates a new connection to -the MongoDB instance running on localhost on the default port and set +the MongoDB instance running on localhost on the default port and sets the current ``db`` to ``myDatabase``: .. code-block:: javascript diff --git a/source/reference/mongo-shell-reference.txt b/source/reference/mongo-shell-reference.txt index 073a67765a4..70e76702a8f 100644 --- a/source/reference/mongo-shell-reference.txt +++ b/source/reference/mongo-shell-reference.txt @@ -100,7 +100,7 @@ Basic Shell Javascript Operations ---------------------------------- The :program:`mongo` shell provides numerous -:doc:`/reference/javascript` for database operations. +:doc:`/reference/javascript` methods for database operations. In the :program:`mongo` shell, ``db`` is the variable that references the current database. The variable is automatically set to the default @@ -299,7 +299,7 @@ The following table provides some common read operations in the * - :method:`db.collection.find( \ ).count() ` - Returns the total number of objects that match the query. - + The :method:`` ignores :method:`limit() ` and :method:`skip() `. For example, if 100 records match but the limit is 10, @@ -307,13 +307,13 @@ The following table provides some common read operations in the faster than iterating yourself, but still take time. * - :method:`db.collection.findOne( \ ) ` - + - Find and return a single object. Returns null if not found. - - The following example selects a single documents in the + + The following example selects a single document in the ``users`` collection with the ``name`` field matches to ``"Joe"``: - + .. code-block:: javascript coll = db.users; @@ -439,7 +439,7 @@ opening new connections from the :program:`mongo` shell. Miscellaneous ------------- -The following table displays some miscellaneous method: +The following table displays some miscellaneous methods: .. list-table:: :header-rows: 1 From 7250575205682abb5d9b06c64392a4557be44f49 Mon Sep 17 00:00:00 2001 From: kay Date: Thu, 20 Dec 2012 17:56:10 -0500 Subject: [PATCH 4/4] DOCS-689 incorporate feedback from jeremy --- source/mongo.txt | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/source/mongo.txt b/source/mongo.txt index 3c1afcb593e..fb6d5804778 100644 --- a/source/mongo.txt +++ b/source/mongo.txt @@ -62,7 +62,7 @@ To start the :program:`mongo` shell and connect to your :doc:`MongoDB use myDatabase - To list the available database, use the command ``show dbs``. See + To list the available databases, use the command ``show dbs``. See also :ref:`mongo-shell-getSiblingDB` to access a different database from the current database. @@ -104,7 +104,7 @@ From the :program:`mongo` shell, you can use the :doc:`shell methods If the :program:`mongo` shell does not accept the name of the collection, for instance if the name contains a space or starts with a number, you can use an alternate syntax to refer to the - collection, as in the following alternates: + collection, as in the following: .. code-block:: javascript @@ -434,11 +434,12 @@ Some useful methods for handling cursors are: cursor has more documents to return. - :method:`next() ` which returns the next document and - moves by one the position of the cursor. + advances the cursor position forward by one. - :method:`forEach(\) ` which iterates the whole cursor and applies the ```` to each document returned - by the cursor. + by the cursor. The ```` expects a single argument which + corresponds to the document from each iteration. For examples on iterating a cursor and retrieving the documents from the cursor, see :ref:`cursor handling `. See