MongoDB

Published: Thursday, 2 July 2015
mongodb

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.

Client

From your shell, run mongo.

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, switch to the database and create a collection by inserting a document.

> use example
switched to db example
> db.exampleCollection.insert({})
WriteResult({ "nInserted" : 1 })

Current database

The client has a current database. Run db by itself to find out what it is.

> db
example

Collections

A collection holds many documents. A document can be considered a JSON object, which may 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"})
WriteResult({ "nInserted" : 1 })

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

List all documents in a collection

> db.animal.find()
{ "_id" : ObjectId("5edcf84cd0be79d61935661a"), "name" : "giraffe" }

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"})
{ "_id" : ObjectId("5edcf84cd0be79d61935661a"), "name" : "giraffe" }

Updating documents

Removing a field from all documents in a collection

> db.example_collection.update({}, {$unset: {unwanted_field:""} }, {multi: true})

multi: true is required to update more than one matching document.

See the db.collection.update reference documentation.

Indexes

Show indexes on a collection

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

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.

When restoring, use the --drop option to drop each collection before repopulating it.

The dump may be restored to another database. Copy the all the files in dump/ to the target mongodb server. Then restore it to a new database named foo_db.

mongorestore dump/db_name/ --db=foo_db