2. echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
3. sudo apt-get update
4. sudo apt-get install -y mongodb-org
After installation let's run it
5. sudo service mongod start
Shell and MongoDB commands:
Now, after the setup part, need to verify the installation is actually working, in order to do so run:
ps aux | grep mongo
Verify that the grep returns a process which is not the grep itself.
let's connect to the MongoDB service, there is a simple console application named surprisingly, mongo.
you should see:
Now, the most basic component is the db parameter, through it we can access other collections and documents. For example:
The shell is one of the most important building blocks, since most of MongoDB documentation is usually referring to the shell commands. Most shell commands can be done using either one of the clients but when understanding the shell it is much more easier to delve into the MongoDB documentation.
In order to use mongo remotely, remove bind_ip: 127.0.0.1 from /etc/mongod.conf
In order to use mongo in a better way please consider using the authorization mechanism and adding the SSL connection.
Each one has his preferred IDE, personally I am a fan of vi, so I am using atom.
First, we create a connection with the URI connection string to local host, with port 27017.
Then, we connect to Database named Tutorial And use a collection named customers .
This is the basic hello world application in mongo, being able to connect to the server.
Let's explain some of the basic operations we just used, if you have the background of SQL, then the correlation between it and Mongo is the following:
Database == Database
Collection == Table
Document == Row
Let's get back to the example of code we just used.
Then we create a person with the name John Dough and some other details and insert it into the database
This is how we insert and populate our database.
Databases has one more trick off its sleeve, query!. our next operation is to query for the same document,
We create an object which represent our search, and we use it with the find method. the find method returns a finditerable object, which represent the dataset of results of our search.
Accessing it can be done using forEach.
There are many JVM libraries, when using the official package com.mongo there is an important pitfall, handling exceptions, for example when the connection string is not a valid server, you would expect to catch it with MongoException/RuntimeException but this does not seem to work. The exception is NullPointerException. stack overflow link. More JVM libraries will be discussed in the next topic.
JVM common libraries
There are several good JVM libraries available around, each has its pros and cons:
MongoDB Java driver - Official, easy to use and provide up to date mechanisms.
Jongo - Best when using Jackson in your application