1. 程式人生 > >Mongodb shell指令碼

Mongodb shell指令碼

Working with the mongo Shell

To display the database you are using, type db:

db

The operation should return test, which is the default database. To switch databases, issue the use <db>helper, as in the following example:

use <database>

To list the available databases, use the helper show

 dbs. See also db.getSiblingDB() method to access a different database from the current database without switching your current database context (i.e. db).

You can switch to non-existing databases. When you first store data in the database, such as by creating a collection, MongoDB creates the database. For example, the following creates both the database myNewDatabase

 and the collection myCollection during the insert() operation:

use myNewDatabase
db.myCollection.insert( { x: 1 } );
  • db refers to the current database.
  • myCollection is the name of the collection.

If the mongo shell does not accept the name of the collection, for instance if the name contains a space, hyphen(連字元), or starts with a number, you can use an alternate syntax to refer to the collection, as in the following:

db["3test"].find()

db.getCollection("3test").find()

For more documentation of basic MongoDB operations in the mongo shell, see:

Format Printed Results

The db.collection.find() method returns a cursor to the results; however, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. The mongo shell will prompt Typeit to iterate another 20 times.

To format the printed result, you can add the .pretty() to the operation, as in the following:

db.myCollection.find().pretty()

In addition, you can use the following explicit print methods in the mongo shell:

  • print() to print without formatting
  • print(tojson(<obj>)) to print with JSON formatting and equivalent to printjson()
  • printjson() to print with JSON formatting and equivalent to print(tojson(<obj>))

For more information and examples on cursor handling in the mongo shell, see Iterate a Cursor in the mongo Shell. See also Cursor Help for list of cursor help in the mongo shell.

Multi-line Operations in the mongo Shell

If you end a line with an open parenthesis ('('), an open brace ('{'), or an open bracket ('['), then the subsequent lines start with ellipsis ("...") until you enter the corresponding closing parenthesis (')'), the closing brace ('}') or the closing bracket (']'). The mongo shell waits for the closing parenthesis, closing brace, or the closing bracket before evaluating the code, as in the following example:

> if ( x > 0 ) {
... count++;
... print (x);
... }

You can exit the line continuation mode if you enter two blank lines, as in the following example:

> if (x > 0
...
...
>