It’s noSQL database for modern type of applications. Database is used by Facebook, Adobe, Google, Sega like bigger and well known companies.
mongoDB is storing data in JSON like format which is called BSON stands for Binary JSON. MongoDB is schema-free, allowing you to create documents without having to define the structure of the document.
This database is used for applications which are related to real-time analytics, content management, the internet of things and mobile applications.
Benefits of MongoDB
- No schema definition is required to create any collections
- Less risk of attacks due to no collection design/structure available
- If you have unstructured data then it’s best choice to use
- Much more faster then SQL database
- Many filters are available to fetch data different ways
Installation
You can install MongoDB on Ubuntu using below commands in terminal window
wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
sudo apt-get update
sudo apt-get install -y mongodb-org
echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-org-shell hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selections
Check MongoDB is installed properly by running below command in terminal
mongo
For Start MongoDB
sudo service mongod start
For Stop MongoDB
sudo service mongod stop
For Restart MongoDB
sudo service mongod restart
Install PHP driver for MongoDB
sudo apt-get install php-mongodb
Simple comparison with MySQL
Mongo DB | MY SQL |
Collection | Table |
Documents | Rows |
Field | Column |
Embedded documents, linking | Joins |
You can You can see more about MongoDB on below URL
https://www.mongodb.com/docs/launch-manage/
Connect to MongoDB using PHP
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); //connection string
Bulk Insert to MongoDB
$bulk = new MongoDB\Driver\BulkWrite; //for insert bulk documents
$document1 = ['title' => 'one'];
$document2 = ['_id' => 'custom ID', 'title' => 'two'];
$document3 = ['_id' => new MongoDB\BSON\ObjectId, 'title' => 'three'];
$_id1 = $bulk->insert($document1); //create query for insert
$_id2 = $bulk->insert($document2);
$_id3 = $bulk->insert($document3);
$result = $manager->executeBulkWrite('local.testDb', $bulk); //execute insert query
In above local is a database name and testDb is a collection name
Select data from collection
Below query is for fetch records which record contains title=’two’
$query = new MongoDB\Driver\Query(array('title' => 'two')); // filter given in array format
$cursor = $manager->executeQuery('local.testDb', $query);