Translate into your own language

Showing posts with label MongoDB. Show all posts
Showing posts with label MongoDB. Show all posts

Sunday, June 26, 2016

Working with Mongo Shell

The mongo shell is an interactive interface to MongoDB. You can use the mongo shell to query and update data as well as perform administrative operations.

The mongo shell is a component of the MongoDB distributions. Once you have installed and have started MongoDB, connect the mongo shell to your running MongoDB instance.

Start the mongo Shell

To start the mongo shell and connect to your MongoDB instance running on localhost with default port:

1. At a prompt in a terminal window, go to your <mongodb installation dir>:

cd <mongodb installation dir>

Type ./bin/mongo to start mongo:

./bin/mongo

If you have added the <mongodb installation dir>/bin to the PATH environment variable, you can just type mongo instead of ./bin/mongo.

When you run mongo without any arguments, the mongo shell will attempt to connect to the MongoDB instance running on the localhost interface on port 27017. To specify a different host or port number, as well as other options, see examples of starting up mongo and mongo reference which provides details on the available options.

Typically users invoke the shell with the mongo command at the system prompt. Consider the following examples for other scenarios.

Core Options

mongo

--shell
Enables the shell interface. If you invoke the mongo command and specify a JavaScript file as an argument, or use --eval to specify JavaScript on the command line, the --shell option provides the user with a shell prompt after the file finishes executing.

--nodb
Prevents the shell from connecting to any database instances. Later, to connect to a database within the shell, see Opening New Connections.

--norc
Prevents the shell from sourcing and evaluating ~/.mongorc.js on start up.

--quiet
Silences output from the shell during the connection process.

--port <port>
Specifies the port where the mongod or mongos instance is listening. If --port is not specified, mongo attempts to connect to port 27017.

--host <hostname>
Specifies the name of the host machine where the mongod or mongos is running. If this is not specified, mongo attempts to connect to a MongoDB process running on the localhost.

To connect to a replica set, specify the replica set name and a seed list of set members. Use the following form:

<replSetName>/<hostname1><:port>,<hostname2><:port>,<...>

For TLS/SSL connections (--ssl), mongo verifies that the hostname of the mongod or mongos to which you are connecting matches the CN or SAN of the mongod or mongos‘s --sslPEMKeyFile certificate. If the hostname does not match the CN/SAN, mongo will fail to connect.

--eval <javascript>
Evaluates a JavaScript expression that is specified as an argument. mongo does not load its own environment when evaluating code. As a result many options of the shell environment are not available.

--username <username>, -u <username>
Specifies a username with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the --password and --authenticationDatabase options.

--password <password>, -p <password>
Specifies a password with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the --username and --authenticationDatabase options. To force mongo to prompt for a password, enter the --password option as the last option and leave out the argument.

--help, -h
Returns information on the options and use of mongo.

--version
Returns the mongo release number.

--verbose
Increases the verbosity of the output of the shell during the connection process.

--disableJavaScriptJIT
New in version 3.2.
Disables use of the JavaScript engine’s JIT compiler.

<file.js>
Specifies a JavaScript file to run and then exit. Generally this should be the last option specified.

To connect to a database on a remote host using authentication and a non-standard port, use the following form:

mongo --username <user> --password <pass> --host <host> --port 28015

Alternatively, consider the following short form:
mongo -u <user> -p <pass> --host <host> --port 28015

Replace <user>, <pass>, and <host> with the appropriate values for your situation and substitute or omit the --port as needed.

Authentication Options

--authenticationDatabase <dbname>

Specifies the database in which the user is created. See Authentication Database.

If you do not specify a value for --authenticationDatabase, mongo uses the database specified in the connection string.

--authenticationMechanism <name>


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>


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 Type it 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()

Tab Completion and Other Keyboard Shortcuts

The mongo shell supports keyboard shortcuts. For example,
Use the up/down arrow keys to scroll through command history. See .dbshell documentation for more information on the .dbshell file.

Use <Tab> to autocomplete or to list the completion possibilities, as in the following example which uses <Tab> to complete the method name starting with the letter 'c':
db.myCollection.c<Tab>

Because there are many collection methods starting with the letter 'c', the <Tab> will list the various methods that start with 'c'.

Exit the Shell

To exit the shell, type quit() or use the <Ctrl-c> shortcut.

Saturday, June 25, 2016

What is collection in MongoDB, how to create and use it

Collections : MongoDB stores documents in collections. Collections are similer to tables in relational databases like Oraclle.

Create a Collection

If a collection does not exist, MongoDB creates the collection when you first store data for that collection.

db.myNewCollection2.insert( { x: 1 } )

db.myNewCollection3.createIndex( { y: 1 } )

Both the insert() and the createIndex() operations create their respective collection if they do not already exist.

Creating a collection using db.createCollection() method 

MongoDB provides the db.createCollection() method to explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules. If you are not specifying these options, you do not need to explicitly create the collection since MongoDB creates new collections when you first store data for the collections.

Because MongoDB creates a collection implicitly when the collection is first referenced in a command, this method is used primarily for creating new collections that use specific options. For example, you use db.createCollection() to create a capped collection, or to create a new collection that uses document validation. db.createCollection() is also used to pre-allocate space for an ordinary collection.

Syntax:

db.createCollection(<name>, { capped: <boolean>,
                                                  autoIndexId: <boolean>,
                                                  size: <number>,
                                                  max: <number>,
                                                  storageEngine: <document>,
                                                  validator: <document>,
                                                  validationLevel: <string>,
                                                  validationAction: <string>,
                                                  indexOptionDefaults: <document> } )

Parameter    Type Description

name    string The name of the collection to create.

options    document Optional. Configuration options for creating a capped collection or                                                         for preallocating space in a new collection.

capped    boolean         Optional. To create a capped collection, specify true. If you                                                                    specify true, you must also set a maximum size in the size field.

autoIndexId    boolean          Optional. Specify false to disable the automatic creation of an                                                                index on the _id field.

size            number Specify a maximum size in bytes for a capped collection. Once a                                                           capped collection reaches its maximum size, MongoDB removes                                                           the older documents to make space for the new documents. The                                                             size field is required for capped collections and ignored for other                                                           collections. it is optional

max                   number Optional. The maximum number of documents allowed in the                                                                 capped collection. The size limit takes precedence over this limit.                                                           If a capped collection reaches the size limit before it reaches                         the maximum number of documents, MongoDB removes old                                                                 documents. If you prefer to use the max limit, ensure that the size                                                           limit, which is required for a capped collection, is sufficient to                 contain the maximum number of documents.

usePowerOf2Sizes boolean         Optional. Available for the MMAPv1 storage engine only.

noPadding boolean         Optional. Available for the MMAPv1 storage engine only.

storageEngine document    Optional. Available for the WiredTiger storage engine only.
                New in version 3.0.
                Allows users to specify configuration to the storage                                         engine on a per-collection basis when creating a collection. The                                                             value of the storageEngine option should take the following form:
               { <storage-engine-name>: <options> } Storage engin configuration                                                         specified when creating collections are validated and logged to the                 oplog during replication to support replica sets with members that                                                         use different storage engines.

validator document                        Optional. Allows users to specify validation rules or expressions                                                            for the collection. For more information, see Document Validation

validationLevel    string                Optional. Determines how strictly MongoDB applies the validation                                                        rules to existing documents during an update.

validationAction string       Optional. Determines whether to error on invalid documents or just                                                       warn about the violations but allow invalid documents to be                                                                   inserted.


Examples


>use test
switched to db test


>db.createCollection("mycollection")
{ "ok" : 1 }


>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

Create a Capped Collection

Capped collections have maximum size or document counts that prevent them from growing beyond maximum thresholds. All capped collections must specify a maximum size and may also specify a maximum document count. MongoDB removes older documents if a collection reaches the maximum size limit before it reaches the maximum document count. Consider the following example:

db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )

This command creates a collection named log with a maximum size of 5 megabytes and a maximum of 5000 documents.

The following command simply pre-allocates a 2-gigabyte, uncapped collection named people:

db.createCollection("people", { size: 2147483648 } )



What is a database in MongoDB, how to create and use it

Database: In MongoDB, a databases hold collections of documents.

MongoDB don't provides any command to create “database“. Actually, you don’t need to create it manually, because, MangoDB will create it on the fly, during the first time you save the value into the collection.

The use Command

MongoDB use DATABASE_NAME is used to create database. The command will create a new database, if it doesn't exist otherwise it will return the existing database.

Syntax:

Basic syntax of use DATABASE statement is as follows:

>use DATABASE_NAME

Example:

If you want to create a database with name <mydb>, then use DATABASE statement would be as follows:

>use mydb
switched to db mydb

To check your currently selected database use the command db

>db
mydb

If you want to check your databases list, then use the command show dbs.

>show dbs
local     0.78125GB
test      0.23012GB

Your created database (mydb) is not present in list. To display database you need to insert atleast one document into it.

>db.movie.insert({"name":"tutorials point"})
>show dbs
local      0.78125GB
mydb       0.23012GB
test       0.23012GB

In mongodb default database is test. If you didn't create any database then collections will be stored in test database.