MongoDB is document based NoSQL database. This means that:
- it has no schema
- it has no relations
- it is agile and scaleable
- stores information in nested documents of two-dimensional key/value pairs.
What are the benefits of using MongoDB?
- you do not have to pre-define your schema or data model
- works nicely with JavaScript
- ideal for client-side applications
Installing MongoDB
Installing MongoDB on Mac with Homebrew
$ brew update
$ brew install mongodb
Add mongodb binaries to your path
$ vi ~/.bash_profile
$ export PATH="/user/local/Cellar/mongodb"
Create data directory
$ sudo mkdir -p /data/db
Make sure that the user account using mongod has access to this directory. If you are getting errors when you run mongod, try the following to test.
$ sudo chmod -R 777 /data/db
$ mongod
You should see “waiting for connections on port 27017”. Accept the Mac prompt about this port. Leave it running or you won’t be able to run Mongo commands.
On ANOTHER TERMINAL, do the following to test
$ mongo
> show dbs
> db
> use db_name
> db.users.save({ name: 'Hello' });
> db.users.find();
{ "_id" : ObjectId("5718f9e188eb6ebd7fd588b7"), "name" : "Hello" }
> db.users.find({name:'Hello'});
> db.users.update({name:'Hello'},{name:'Hello World'});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.remove({})
> db.users.remove({name:'Hello'})
> exit
This is called the Mongo Shell. It is an interactive JavaScript interpreter. You can many commands on it like:
> for(i=0;i<5;i++) print("number "+i);
Following are number, string, and object declarations
> a = 1
> b = "str"
> c = {"d":1}
> c.d
> c["d"]
Objects are denoted in BSON format. See bsonspec.org. Last two lines show how to access object variables.
For help, type the following in Mongo Shell
> help
> help keys
Mongo CRUD
CRUD stands for Create Retrieve Update Delete. These refer to the creating, retrieving, updating, and deleting rows. Following tables shows statements used by SQL and Mongo for CRUD
– | SQL | Mongo |
---|---|---|
C | Insert | Insert |
R | Select | Find |
U | Update | Update |
D | Delete | Remove |
In MongoDB, CRUD operations exist as methods or functions in a programming language API. A query language is not used.
Following are the CRUD command you need to know:
Create Database
use Continents
List databases
show databases
Create Collection (Mongo term for table)
db.createCollection("Countries")
db.createCollection("Dummy")
List collections
show collections
drop collection
db.Dummy.drop()
Insert data in a collection
a = {"name":"Canada", "capital":"Toronto"}
db.Countries.save(a)
Query data from collection
db.Countries.find({"name":"Canada"});
Update a Document (row) in a collection
db.Countries.update(
{"name":"Canada"},
{$set: {"capital":"Ottawa"}}
)
Remove a document
db.Countries.remove({_id:100...})
Copy database
db.CopyDatabase("Countries", "Pays")
Making PHP and MongoDB to work together
Making PHP and MongoDB to work together is a two part process.
- Install MongoDB driver for PHP
- Install PHP library for MongoDB
Type the following in your terminal:
$ brew install homebrew/php/php55-mongodb
My PHP version is 5.5. If you are running a different version, you would need to install a different extension.
To test whether the driver was installed correctly, save the following PHP code as test.php
<?php
print_r(phpversion("mongodb"));
?>
Run the code
$ php test.php
Your output should be something like the following:
1.1.8
The easiest way to install PHP library for MongoDB is to use composer. Composer is a package handler for PHP like PECL and PEAR. First of all, check whether you have composer installed on your system.
$ which composer
The following commands will install composer on a Mac
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer
$ composer init
Then install PHP MongoDB library
$ composer require "mongodb/mongodb"
Save the following PHP code as test1.php
<?php
// use Composer packages
require 'vendor/autoload.php';
// connect to MongoDB
$client = new MongoDB\Client("mongodb://localhost:27017");
// use/create "testdb" database and "testtable" table
$collection = $client->testdb->testtable;
// insert data in the database
$result = $collection->insertOne( [ 'name' => 'hello', 'description' => 'world' ] );
// get the inserted object id
echo "Object ID = '{$result->getInsertedId()}'";
?>
Run the code
$ php test1.php
You should get an output like the following
Object ID = '57c464e99d74ed076a3c2301'
To check whether the data was inserted correctly, type mongod on one terminal and mongo on another terminal. In the mongo terminal type the following:
> show dbs
local 0.000GB
testdb 0.000GB
> use testdb
switched to db testdb
> db.getCollectionNames()
[ "testtable" ]
> db.testtable.find()
{ "_id" : ObjectId("57c464e99d74ed076a3c2301"), "name" : "hello", "description" : "world" }
The first command lists all databases. Second command is selects the database you want to work with. The third command lists all collections (tables). The last command lists the contents of the collection.
To fetch contents of a selection using PHP code,
<?php
require 'vendor/autoload.php';
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->testdb->testtable;
// find data
$rs = $collection->find( [ 'name' => 'hello', 'description' => 'world' ] );
// fetch the collection
foreach ($rs as $rw) {
print $rw['_id'] . "\t" . $rw['name'] . "\t" . $rw['description'] . "\n";
}
?>
Output
57c464e99d74ed076a3c2301 hello world
Note the use on find() instead of insertOne().