MongoDB the Good to Know

Recently I have been working with MongoDB. Here is some highlight that might help you to take the decision to use that No-Sql database.

In MongoDB, write operations are atomic at the document level. If you design your data to use reference (which is possible) forget about atomic transaction. Also, if you design by referencing other document, it will not be possible to get the information with a single query.

It is possible to query MongoDB with operator such as comparing with $gt, $gte, $lt, $lte, $in, $nin, $ne. Logical operation exist with $or, $and, $not, $not. Others type of operator exists and can be used for querying the database or to project. Here are some example.

db.users.insert({name:"patrick", age:30})
db.users.insert({name:"mélodie", age:26})
db.users.insert({name:"vincent", age:30})
db.users.insert({name:"julie", age:28})
db.users.find({age:{$lt:30}}) // Return 2 elements

When you document get over 16 megs, Mongo divide it into part. The need of GridFS is than required to reassemble every part of the document.

In MongoDB you can allow the system to generate the unique identifier by not setting any _id. But, you can also take the liberty to assign the _id when inserting your document.

It is better to store one to many reference into the “one side”. This way, you do not have a huge array in the “many side”. You can also reference something that does not exist yet. For example, if A reference B, you can insert A with a reference to B and then insert B.

It is possible to set index, like in SQL, to improve performance. This can be done with the ensureIndex method. This method is available on the database.

db.users.ensureIndex({name:1})

It is possible to store in a string information such as a hiearchical path and then query against that string property with a regex to find.

It is possible to write with the MongoDb command insert, update, findAndModify and remove.

The update command can be executed against a collection. This one has three parameters. The first one is the query. You can specify the unique identifier of the data your want to update or to any other criteria. This can be useful for embedded resource to query multiple documents that has the same embedded information. The second parameter is what we are updating. We can update the whole document or a part of it. It is also possible to push ($push) information into an existing array or to increment/decrement value of a field. The following example come from the MongoDB website and it update a book by its ID only if this one has available book on the shelve. It update by decreasing the number of available copies and push a new entry about who checkout the book. This is all done atomicly.

db.books.update (
   { _id: 123, available: { $gt: 0 } },
   {
     $inc: { available: -1 },
     $push: { checkout: { by: "abc", date: new Date() } }
   }
)

Doing operations like update, insert, delete return some information into a WriteResult object. Some properties like the number of found element by the query, the number of inserted or modified document are returned. The number of inserted can be above 0 when updating if in the third parameter of the update you specify the option of inserting if not found.

When defining an index on an array, MongoDB creates index entries for each element. This mean that if you have a document with an index on an array of 3 elements that in the backend the information will be set in three index collection. For example, if you have a car document with an array of color and that you set an index on the color array the document will be indexed 3 times and also stored one time as the car itself. This has an impact in the inserting time (like in SQL).

If you are working with money and want to be exact, you need to multiply your number to have an integer. For example, storing 9.99 with a precision of 2 decimals would require you to store 999 in MongoDB. By then, you have to divide by 100 to get back the real value. Depending of the precision you want, you multiply and divide by the power of 10 desired.

The primary key is defined with MongoDB ObjectId. This ObjectId is generated by using the Unix TimeStamp, the machine identifier, the process id and a random value. It’s result look like a GUID. You can generate one by calling ObjectId()
ObjectId

Installing MongoDB on a Windows Machine

The first step is to install MongoDB on your machine. You can go on the official website, in the top menu, you will see Download. Click the Download link (http://www.mongodb.org/downloads) and then select the Windows version. You can download the 64 bits or 32 bits. In this tutorial of MongoDB we will use the MongoDB 64 bits for Windows. The file is about 132 megs and is a setup.

MongoDbSetup

The installation is pretty straight forward. You can select the typical installation to have a basic setup. During the installation, you will have to accept to elevate the permission.

From here, it is time to open a Command Prompt with administration right. Let’s go in the folder we just installed MongoDB. Since we have installed the typical package with the 64 bits version, the installation should be in program file.

MongoDbConsole

You can after that configure MongoDB. The next steps are taken directly from MongoDB documentation. You must create a directory to save the content. This can be anywhere so let’s do a data folder at the root of the installation path. The md command let you create a directory. The code below is what you can write to create the default path that MongoDB uses.

cd "C:\Program Files\MongoDB 2.6 Standard"
md \data\db

Then, you can start MongoDB.

cd bin
mongo.exe

Me, the first time I start MongoDB I got a warning followed by an error saying that it was not possible to connect.

C:\Program Files\MongoDB 2.6 Standard\bin>mongo.exe
MongoDB shell version: 2.6.4
connecting to: test
2014-09-10T13:34:40.878-0700 warning: Failed to connect to 127.0.0.1:27017, reason: errno:10061 No connection could be made because the target machine actively
refused it.
2014-09-10T13:34:40.882-0700 Error: couldn’t connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
exception: connect failed

Than I realized that I was launching mongo.exe instead of mongod.exe. Once the administration console lunch the mongod.exe you can start a new console (no need to have administration privileges on this one) and start mongo.exe. Here is what you should see.

MongoDbConsole

Do not forget to specify the –dbpath when starting the mongod.exe because otherwise it will store everything on you c:\ drive.

Basic Commands

Here is few commands that may be useful during the development.
dbs shows the database you have

show dbs

You can create new database or switch the a database by using the use command.

use mydb

Information are added into collection. You can add data into a collection with the command db..insert().
Here is an example of three insert into a collection named “testdata” of the dotnet database.

use dotnet
db.testdata.insert({id:1})
db.testdata.insert({id:2})
db.testdata.insert({id:3,name:"three"})

It is possible to see if the collection of the active database really exist with show collections command.

show collections

The last command that is really useful is to see the content of a collection. You can use the find() command.

db.testdata.find()

Keep in mind that if you see nothing it might be because you typed the collection name with the wrong case sensitivity. MongoDB is case sensitive.
Here is screenshot of the output of all commands that we just discussed.
MongoBasicCommands