Home > Backend Development > PHP Tutorial > Php MongoDB Connectivity

Php MongoDB Connectivity

PHP中文网
Release: 2024-12-03 11:26:40
forward
990 people have browsed it

Php provides mongodb driver to connect with mongoDB database. After installing it, we can perform database operations by using the php. Here, we are using Ubuntu 16.04 to create an example. This example includes the following steps.

1) Installing Driver

  1. $ pecl install mongodb  

MongoDB Php mongodb connectivity 1

2) Edit php.ini File

It is store in the apache server directory /etc/php/7.0/apache2/php.ini

  1. $ extension = mongodb.so  

MongoDB Php mongodb connectivity 2

3) Install mongo-php library

Following is the preferred way of installing this library with Composer.

  1. $ composer require mongodb/mongodb  

MongoDB Php mongodb connectivity 4

4) Create Php Script

// connect.php

  1. require 'vendor/autoload.php';  
  2. // Creating Connection  
  3. $con = new MongoDBClient("mongodb://localhost:27017");  
  4. // Creating Database  
  5. $db = $con->javatpoint;  
  6. // Creating Document  
  7. $collection = $db->employee;  
  8. // Insering Record  
  9. $collection->insertOne( [ 'name' =>'Peter', 'email' =>'peter@abc.com' ] );  
  10. // Fetching Record  
  11. $record = $collection->find( [ 'name' =>'Peter'] );  
  12. foreach ($record as $employe) {  
  13. echo $employe['name'], ': ', $employe['email']."
    ";  
  14. }  
  15. ?>  

5) Execute Php Script

Execute this script on the localhost server. It will create database and store data into the mongodb.

  1. localhost/php/connect.php  

MongoDB Php mongodb connectivity 5

6) Enter into Mongo Shell

After executing php script, we can see the created database in mongodb.

  1. $ mongo  

MongoDB Php mongodb connectivity 6

6.1. Show Database

The following command is used to show databases.

  1. > show dbs  

MongoDB Php mongodb connectivity 7

6.2. Show Collection

The following command is used to show collections.

  1. > show collections  

MongoDB Php mongodb connectivity 8

6.3. Access Records

  1. > db.employee.find()  

MongoDB Php mongodb connectivity 9

Well all set, this is working fine. We can also perform other database operations as well.

The above is the detailed content of Php MongoDB Connectivity. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:javatpoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template