Last active
June 16, 2016 00:27
-
-
Save thiagoguarnieri/e8791af733ccbb5f864afcf884cb117d to your computer and use it in GitHub Desktop.
MongoDB PHP Installation and operation (Ubuntu 14.04)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#install mongo db | |
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 | |
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list | |
sudo apt-get update | |
sudo apt-get install -y mongodb-org | |
#install pecl | |
sudo apt-get install php5-dev php5-cli php-pear | |
#requisites | |
apt-get install pkg-config | |
Install mongo extension | |
pecl install mongodb | |
add "extension=mongodb.so" to php.ini | |
#its necessary to use composer to get the libraries. Go to https://getcomposer.org/download/ and make the download. | |
#after, put the downloaded files into the project folder and execute: | |
php composer.phar require "mongodb/mongodb=^1.0.0" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
//connect | |
$client = new MongoDB\Client("mongodb://localhost:27017"); | |
//select db->table | |
$collection = $client->examples->nomes; | |
//inserting | |
$result = $collection->insertOne(['name' => 'paul', 'lastname' => 'stanley']); | |
//inserting many. Use array | |
$data = array(array('name' => 'rick', 'lastname' => 'turing'),array('name' => 'alan', 'lastname' => 'rubin')); | |
$result = $collection->insertMany($data); | |
//finding one | |
$result = $collection->findOne([ 'lastname' => 'turing']); | |
//finding various | |
$result = $collection->find(['lastname' => 'turing']); | |
//list all and sort by lastname and name ascendent | |
$result = $collection->find([],['sort' => ['lastname' => 1, 'name' => 1],]); | |
//group by lastname, count lastname e order by count | |
$result = $collection->aggregate([['$group' => ['_id' => 'lastname', 'count' => ['$sum' => 1]]],['$sort' => ['count' => -1]],]); | |
//printing | |
foreach ($result as $document) {echo $document['name'].",".$document['lastname']. "\n";} | |
//create indexes to accelerate queries | |
$collection->createIndex(['name' => 1, 'lastname' => 1]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment