MongoDB notes

This post is meant as a catch all for those bits of information which do not need a full post (ofcourse this doesn’t mean I won’t create a full post at a later date should the need arise).

Atomicity

Whilst MongoDB guarantees atomicity of a write operation as a single document level there is no such guarantee on multiple documents.

So for example if one is creating a relational style model with related data in more than one document (i.e. not an embedded relational model) then writing to the multiple documents is NOT atomic.

Indexes

Be default an index is created for the _id of a document. To create our own we use the ensureIndex method on a collection.

The MongoDB documentation states that

  • Each index requires at least 8KB od data space
  • Whilst query performance on the indexed data is increased the write operation will see a negative performance impact – therefore indexes can be expensive if there’s a high write to read ratio on documents

Overriding Default functionality

As mongodb uses JavaScript we can use JavaScript code to override some default functionality.

Let’s say for example, we want to stop users accidentally dropping a database. We can override the dropDatabase function thus

DB.prototype.dropDatabase = function() {
   print("dropDatabase disabled");
}

db.dropDatabase = DB.prototype.dropDatabase;

Loading scripts from the shell

Typing in code, such as the above override of the dropDatabase function every time, would end up being time consuming. Being that this is JavaScript it may come as no surprise to find out that the mongo shell can load script files.

Using load(‘myscript.js’);

Loading scripts at startup

In the above example, we’ve created a script which we might need to load every time we start mongo. So it’d be better if we could just load the script file automatically at startup.

So to load scripts at startup on a Windows machine, place the script file into c:\users\\.mongorc.js

Note: It’s also possible that we might want to ignore scripts at startup when debugging, in such a case we start mongo using

mongo –norc

More to come…