MongoDB

1. Installation

Under ubuntu, add the package "mongodb-clients" and "mongodb-server"

Configuration

/etc/mongodb.conf holds the server configuration.

bind_ip

bind_ip tells the server which interfaces to listen on. It is comma separated.

2. Client

From your shell, run mongo.

3. Databases

A database holds many collections.

Show databases

One mongod server may hold many databases.

> show dbs
database        0.0625GB
example 0.0625GB
exampledb       0.0625GB
rover1  0.0625GB
>

Database creation

From the client, to create a 'example' database, run

> use example switched to db example

Current database

Run 'db' by itself.

> db
example

4. Collections

A collection holds many documents. A document can be considered a JSON object, which could have nested fields.

List all collections in a db

> use exampledb
switched to db exampledb
> show collections
animal
system.indexes

Inserting a document

To insert into the 'animal' collection of the current database, run:

[db.animal.insert({name: "giraffe"})

It will also create the collection if it does not exist.

List all documents in a collection

> db.animal.find()

The above shows documents in the 'animal' collection of the current database.

List some documents in a collection

Finds all documents in the 'animal' collection where name is equal to 'giraffe'

db.animal.find({"name":"giraffe"})

Indexes

Show indexes on a collection

> db.animal.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "exampledb.animal",
                "name" : "_id_"
        }
]

5. mongodump and mongorestore

This is used for backing up and restoring documents

To dump only a single database, use

mongodump -d db_name

This will create a directory dump/db_name/ with various json and bson files inside it.