Relational Database

Document Oriented DataBase

Getting Started with MongoDB

$ mongod
all output going to: /usr/local/var/log/mongodb/mongo.log

By default, mongo looks for a database server listening on port 27017 on the localhost interface.

To connect to a server on a different port or interface, use the --port and --host options.

Podemos también usar un fichero de configuración:

[~/javascript/expressjs/coffee-mongo(master)]$ cat /usr/local/etc/mongod.conf
# Store data in /usr/local/var/mongodb instead of the default /data/db
dbpath = /usr/local/var/mongodb

# Append logs to /usr/local/var/log/mongodb/mongo.log
logpath = /usr/local/var/log/mongodb/mongo.log
logappend = true

verbose = v 
# Only accept local connections
bind_ip =

y ejecutarlo con la opción --config:

$ mongod --config /usr/local/etc/mongod.conf

[~/src/coffee/coffeepress.bak(master)]$ mongo
MongoDB shell version: 2.4.8
connecting to: test
Server has startup warnings: 
Mon Apr 13 21:53:16.204 [initandlisten] 
Mon Apr 13 21:53:16.204 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000

After starting the mongo shell, your session will use the test database by default. At any time, issue the following operation at the mongo shell to report the name of the current database:

> db

From the mongo shell, display the list of databases, with the following operation:

> show dbs
coffeepress     0.203125GB
coffeepress-dev 0.203125GB
dict_dev        0.203125GB
example 0.203125GB
local   0.078125GB
mean    0.203125GB
my_perpetuity_database  0.203125GB
mydb    0.203125GB
sinatra-example-dev     0.203125GB
test    0.203125GB

Switch to a new database named example, with the following operation:

> use example
switched to db example
At any point, you can access help for the mongo shell using
> help                    help on db methods             help on collection methods                    sharding helpers                    replica set helpers
        help admin                   administrative help
        help connect                 connecting to a db help
        help keys                    key shortcuts
        help misc                    misc things to know
        help mr                      mapreduce

        show dbs                     show database names
        show collections             show collections in current database
        show users                   show users in current database
        show profile                 show most recent system.profile entries with time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memory, 'global' is default
        use <db_name>                set current database                list objects in collection foo { a : 1 } )     list objects in foo where a == 1
        it                           result of the last line evaluated; use to further iterate
        DBQuery.shellBatchSize = x   set default number of items to display on shell
        exit                         quit the mongo shell

Furthermore, you can append the .help() method to some JavaScript methods, any cursor object, as well as the db and db.collection objects to return additional help information.

DB methods:
        db.auth(username, password)

Create a Collection and Insert Documents

In this section, you insert documents into a new collection named testData within the new database named mydb.

Create two documents named j and k by using the following sequence of JavaScript operations:

> j = { name : "mongo" }
{ "name" : "mongo" }
> k = { x : 3 }
{ "x" : 3 }
Insert the j and k documents into the testData collection with the following sequence of operations:
> db.testData.insert( j )
> db.testData.insert( k )
When you insert the first document, the mongod will create both the mydb database and the testData collection.
> show collections
The mongo shell will return the list of the collections in the current (i.e. mydb) database. At this point, the only collection with user data is testData.

Confirm that the documents exist in the testData collection by issuing a query on the collection using the find() method:

> db.testData.find()
{ "_id" : ObjectId("552d751969c6f61bfbe4e6ed"), "name" : "mongo" }
{ "_id" : ObjectId("552d751a69c6f61bfbe4e6ee"), "x" : 3 }
All MongoDB documents must have an _id field with a unique value. These operations do not explicitly specify a value for the _id field, so mongo creates a unique ObjectId value for the field before inserting it into the collection.

Insert Documents using a For Loop or a JavaScript Function

To perform the remaining procedures in this tutorial, first add more documents to your database using one or both of the procedures described in Generate Test Data.

Insert Multiple Documents Using a For Loop

From the mongo shell, use the for loop. If the testData collection does not exist, MongoDB will implicitly create the collection.

> for (var i = 1; i <= 25; i++) {
...    db.testData.insert( { x : i } )
... }
Use find() to query the collection:
> db.testData.find()
{ "_id" : ObjectId("552d751969c6f61bfbe4e6ed"), "name" : "mongo" }
{ "_id" : ObjectId("552d751a69c6f61bfbe4e6ee"), "x" : 3 }
{ "_id" : ObjectId("552d791269c6f61bfbe4e6f0"), "x" : 1 }
{ "_id" : ObjectId("552d791269c6f61bfbe4e6f1"), "x" : 2 }
{ "_id" : ObjectId("552d791269c6f61bfbe4e6f2"), "x" : 3 }
{ "_id" : ObjectId("552d791269c6f61bfbe4e701"), "x" : 18 }
Type "it" for more
Iterate through the cursor. The find() method returns a cursor. To iterate the cursor and return more documents, type it in the mongo shell. The shell will exhaust the cursor and return these documents:
> it
{ "_id" : ObjectId("552d791269c6f61bfbe4e702"), "x" : 19 }
{ "_id" : ObjectId("552d791269c6f61bfbe4e708"), "x" : 25 }

Working with the Cursor

When you query a collection, MongoDB returns a “cursor” object that contains the results of the query. The mongo shell then iterates over the cursor to display the results. Rather than returning all results at once, the shell iterates over the cursor 20 times to display the first 20 results and then waits for a request to iterate over the remaining results. In the shell, enter it to iterate over the next set of results.

The procedures in this section show other ways to work with a cursor. For comprehensive documentation on cursors, see Iterate the Returned Cursor.

Casiano Rodríguez León