MongoDB

A Short Introduction

Heinrich Göbl

www.goebl.com

About me

  • Heinrich Göbl
  • IT-Freelancer (Architecture, Software-Development)
  • Focus on Java EE
  • “MongoDB is the backend db for my Android apps”

What is MongoDB?

Focus of MongoDB



(from: MongoDB The Definitive Guide, O'Reilly)

Some facts

Database Landscape

Terminology

RDBMSMongo
TableCollection
Row(s)BSON Document
ColumnBSON Field
IndexIndex
JoinEmbedded Document
PartitionShard
Partition KeyShard Key

Philosophy

Data to Big Data

Document Data Model

var book = {
  title: 'MongoDB: The Definitive Guide',
  authors: [
    { lastName: 'Chodorow', firstName: 'Kristina' },
    { lastName: 'Dirolf', firstName: 'Michael' }
  ],
  tags: ['NoSQL', 'Database', 'BigData', 'Programming'],
  pages: 195,
  published: 2010
};

Insert

db.books.save(book);

// primary key '_id'
// generated by client driver
// e.g. 4fba97070f318c1e73763350

book._id;

Simple Queries 1

db.books.find(); // find all

// get count of all docs
db.books.count();
db.books.find().count();

// find by primary key (_id)
db.books.findOne({
    _id: ObjectId("4fba97190f318c1e73763353")
});

Simple Queries 2

db.books.find({ title: 'JavaScript Patterns' });

db.books.find({ title: /^MongoDB/ });

db.books.find({ title: /^MongoDB/,   // and
                pages: {$gt: 200} });

Query Deep Structures

db.books.find({
  'authors.lastName': 'Katz'});
db.books.find({
  'authors.lastName':
    {$in: ['Katz', 'McCaw']} });
db.books.find({
  $or: [
    {'authors.lastName': 'Katz'},
    {'authors.lastName': 'McCaw'}
  ]});

Query Multivalued Fields

db.books.find({authors: {$size:2} });

db.books.find(
  { tags: 'Programming' });

db.books.find({
  tags: {$all: ['Programming',
                'JavaScript']}
  });

Projection, Sort, Limit

db.books.
    find({/* all */},
    {title: 1, pages: 1}).
    sort({title: 1}).
    limit(4);

Update

db.books.update({title: /Good Parts/},
                {$inc: {pages: 3}});

db.books.update({title: /in Action/},
    {$set: {publisher: 'Manning'}},
    false, true);

db.books.update({},
    {$addToSet: {tags: 'Programming'}},
    false, true);

Delete

db.books.remove({_id: mybook._id});

db.books.remove({tags: 'Cooking'});

db.books.remove(); // truncate col
db.books.remove({/* ... */}, {$atomic:true});
// blocking!

count, distinct, group

db.runCommand({count: 'books',
               query: {published: 2012}});

db.runCommand({distinct: 'books', key:'tags'});

db.runCommand({group: {
    ns: 'books',
    key: { published: true },
    $reduce: function (obj, prev) {
        prev.pages += obj.pages;
    },
    initial: { pages: 0 }
}});

runCommand

db.runCommand({ dropDatabase: 1 });

db.runCommand({ getLastError: 1 });

db.runCommand({ serverStatus: 1 });

db.runCommand({ shutdown: 1 });

Map-Reduce


db.runCommand({ mapreduce: 'collection_name',
    map: my_map_function,
    reduce: my_reduce_function /*, ...*/});

Sample Document

{ "title": "MongoDB in Action",
  "authors": [
    { "lastName": "Banker",
      "firstName": "Kyle" }
  ],
  "tags": [ "NoSQL", "Database", "Programming" ],
  "pages": 311
}

map function


var map = function () {
  var doc = this;
  doc.tags.forEach(function (tag) {
    emit(tag, { pages: doc.pages });
  });
};

reduce function


var reduce = function (key, values) {
    var result = { pages: 0 };
    values.forEach(function (value) {
        result.pages += value.pages;
    });
    return result;
};

Map-Reduce Example

var map = function () {
        var doc = this;
        doc.tags.forEach(function (tag) {
            emit(tag, { pages: doc.pages });
        });
    }, reduce = function (key, values) {
        var result = { pages: 0 };
        values.forEach(function (value) {
            result.pages += value.pages;
        });
        return result;
    };
db.books.mapReduce(map, reduce, {out: {inline: 1}});

Indexes

db.books.ensureIndex({"title": 1}, {unique: true});

db.books.ensureIndex({"authors.lastName": 1});

db.books.ensureIndex({"tags": 1});

db.books.getIndexes();

db.books.dropIndex('title_1');

Import / Export

mongoexport -d test -c books > mongo.books.txt

mongo test --eval "db.books.remove()"

mongoimport -d test -c books --file books.txt

mongoexport -d test -c books --jsonArray > books.json
mongoimport -d test -c books --jsonArray < books.json

Replica Sets

Replica Sets

Replica Sets

Replica Sets

Sharding

MongoS

Reading

Internet


Books

Credits

Questions?

Thank you!

// my mail address
'hgoebl+goebl.com'.replace('+', '@')