MongoDb Introduction

NoSQL

  • Key-value stores often only support get, put, and delete operations on a primary key.
  • Document stores are similar to key-value stores, but store the value in a format. For MongoDb it is a JSON format. Additional filtering can then be done on the information in the Document, or even just a portion of the Document can be returned. Transactions are usually per Document, but can also include multiple Documents depending on the database.

An essential difference of all NoSQL databases to the relational databases is the transaction security. While relational databases are based on ACID transactions i.e. atomic, consistent, isolated and durable transactions, NoSQL databases are more BASE i.e. available, scalable, possibly consistent. The latter has a big advantage.

Eventually consistent means that the whole cluster, which are databases that are synchronized with each other, will eventually have the same data state. The DNS system is not always consistent, but it will be at some point, as long as there are no more updates.

The big advantage of eventually being consistent is that the databases don’t always have to agree with each other as soon as an update happens. So a network failure between two databases can’t do anything, because the primary database will still allow updates and all secondary databases will switch to read access.

Mongo-Db

Terminology

  • A Table is in Mongo-Db a Collection
  • A Row is in Mongo-Db a Document
  • A RowId is in Mongo-Db the _id key
  • A join can be made with the aggregate function
  • A Select is made with the find function.

Cluster

In Mongo-Db, multiple databases can be joined together so that they form a cluster. The primary database is then automatically selected. If a network error occurs, so that all databases can no longer communicate with each other, the databases that represent the majority choose a new primary database.

Query-Example

db.unicorns.insert({
	name: "Aurora", 
 	gender: "f",
	weight: 450, 
	loves: ["apple", "grape"], 
	birthday: new ISODate('2013-04-15')
})
db.unicorns.find({	
	gender:"f",
	loves:"apple"
})
	
db.unicorns.update(
	{name: "Roooooodles"},
	{$set: {weight: 590}}, 
	{upsert: false}
)
db.unicorns.update(
	{name: "Aurora"}, 
	{$push: {loves: "sugar"}}
)
db.unicorns.find({
	gender:"m", 
	$and:[{weight:{$gte:600}}, {weight:{$lte:900}}]
})
db.address.aggregate([
	{$match: {street: "Blumenstrasse 13"}},
	{$lookup : {
		from: "persons", 
		localField: "_id", 
		foreignField: "address", as: "persons"}},
	{$project: {_id: 0, street: 1}}
])