perjantai 4. maaliskuuta 2016

MongoDB server learnings

Today I just needed to learn what is MongoDB. First I watched these four episodes what is MongoDB and got the idea. I really recommend watching these if you have no idea what mongo is.

MongoDB is "file based" database. MongoDB has collections and inside colletions we have documents which represents our relational database model.

So this is how mongoDB looks like. Compared to MySQL relational database, we have rows:

Student_id, score, first_name, last_name and so on. MongoDB format is called BSON, its almost like JSON format:

To install mongodb on linux platform:

sudo apt-get install mongodb-server

And php driver for mongo

Install MongoDB PHP Driver

sudo apt-get install php5-dev php5-cli php5-mongo php-pear -y

sudo pecl install mongoOpen your php.ini file and add to it:

Restart apache.
by default mongodb server will be installed on port 27017. Mongodb commands are pretty similar to mysql, here I found good examples:

Create new index.php file and insert following:

   // connect to mongodb
   $m = new MongoClient();

   echo "Connection to database successfully";
   // select a database
   $db = $m->mydb;

   echo "Database mydb selected";

MongoDB will create database automatically if it doesnt exist. You should be creeted with message:

Connection to database successfully
Database mydb selected

Mongo Shell

MongoDB is javascript like preprocessor or something like that. To login to MongoDB server, say mongo

Then you can try to type: for(i=0; i<5; i++) print("hello"); in the shell and Mongo should print hello five times.

show dbs shows current databases.
db shows the current selected database
use databasename selects database
db.first.insert({"name": "test"}) creates new collection to database.
db.first.find() prints the collection
db.first.find().forEach(printjson) prints in json format

Ei kommentteja:

Lähetä kommentti