PHP connection MongoDB Database and CRUD operation detailed

Source: Internet
Author: User
Tags findone install mongodb mongoclient mongodb php mongodb
Preface

The previous operation facing MongoDB has been done through the MONGO client process. But in reality, our operations on MONGODB data are often implemented through appropriate programs, such as PHP, Java, or Python. So how to operate MongoDB in PHP. In fact, it's very simple, like operating MySQL, they are loaded into PHP as an extension module.
Of course, first have to install Mongodb,win under installation can refer to (http://blog.csdn.net/hsd2012/article/details/51279472), Linux installation can refer to (http:// blog.csdn.net/hsd2012/article/details/51286495). Second, you have to build a PHP execution environment. Because I am in the local test, uses the win system, therefore uses the wampserver to build the PHP execution environment. configuring MongoDB in PHP

Configuring MongoDB in PHP.ini is fairly straightforward, and you just need to add the following code

Extension=php_mongo.dll  

The main note is that the Php_mongo.dll version must correspond to the current version of PHP. Otherwise, there will be an incompatible error.
About Php_mongo.dll downloads can be downloaded to Http://pecl.php.net/package/mongo. There are many versions available to choose from.
Because I use PHP version under Win32 is 5.5.12, the following figure:

So I downloaded the following version Php_mongo.dll

Note: (1) thread safe ' (thread safety) is running on Apache to extend the module PHP, if you run PHP in CGI mode, select non-thread safe mode (' non-thread safe '). (2) 32-bit system selection, 86 end file, 64 Select end of 64 file.
After the configuration, the output phpinfo (), you can see the following effect, representing the configuration OK.
connecting MongoDB in PHP

First you have to open the MongoDB service, please refer to (http://blog.csdn.net/hsd2012/article/details/51279472)

We all know that the MySQL database is connected in PHP, We can use the mysqli or PDO class, the details can be referred to (http://blog.csdn.net/hsd2012/article/details/51130098), then the connection MongoDB whether there are corresponding classes. The answer is yes. This class is mongoclient. It is the connection Manager for PHP and MongoDB, responsible for creating and managing connections. The structure of the class is as follows:

mongoclient {/* constant */const VERSION; Const string default_host = "localhost"; const int default_port = 27017; c
Onst string rp_primary = "PRIMARY";
Const string rp_primary_preferred = "primarypreferred";
Const string rp_secondary = "secondary";
Const string rp_secondary_preferred = "secondarypreferred";
Const string rp_nearest = "Nearest";
/* Attribute/public Boolean $connected = FALSE;
public string $status = NULL;
protected string $server = NULL;
protected Boolean $persistent = NULL; /* Method/Public __construct ([string $server = "mongodb://localhost:27017" [, Array $options = Array ("Connect" => TRUE
]]) public bool Close ([boolean|string $connection]) public bool Connect (void) public array dropdb (mixed $db) Public MongoDB __get (string $dbname) public static array getconnections (void) public array gethosts (void) public Array getreadpreference (void) public array getwriteconcern (void) public bool Killcursor (string $server _hash, int| MongoiNt64 $id) public array Listdbs (void) public mongocollection selectcollection (string $db, string $collection) Publi  C MongoDB selectdb (string $name) public bool Setreadpreference (string $read _preference [, array $tags]) Setwriteconcern (mixed $w [, int $wtimeout]) public string __tostring (void)}

With the above class, we can now begin to write the program that connects MongoDB.

Linked server
$m = new Mongoclient ();
Select a database
$db = $m->school;
Select a collection (The Mongo "set" corresponds to the "table" of the relational database)
$collection = $db->student;
querying MongoDB data in PHP

In the PHP mongodb extension module, the mongocollection is provided for the curd operation of the data. First, let's look at the mongocollection structure.

mongocollection {/* constant */const int ascending = 1; const int descending =-1;/* Fields/public MongoDB $db = NULL;
public integer $w;
public integer $wtimeout; /* Method */Public array aggregate (array $pipeline [, array $options]) public mongocommandcursor aggregatecursor (array $command [, Array $options]) public mixed Batchinsert (array $a [, array $options = Array ()]) public __construct (Mo Ngodb $db, string $name) public int count ([Array $query = Array () [, int $limit = 0 [, int $skip = 0]]] public arra  Y createdbref (mixed $document _or_id) public bool CreateIndex (array $keys [, array $options = Array ()]) public array Deleteindex (String|array $keys) public array deleteindexes (void) public array distinct (string $key [, Array $quer (Y]) public array drop (void) public bool Ensureindex (String|array $key |keys [, Array $options = Array ()]) public M Ongocursor find ([Array $query = Array () [, Array $fields = Array ()]]) public array findandmodifY (array $query [, array $update [, array $fields [, array $options]]]) public array findone ([Array $query = Array () [, Array $fields = Array () [, Array $options = Array ()]]] Public mongocollection __get (string $name) public array getdbref (array $ref) public array getindexinfo (void) PU Blic string getName (void) public array getreadpreference (void) public bool Getslaveokay (void) public array Getwri Teconcern (void) public array group (mixed $keys, array $initial, Mongocode $reduce [, Array $options = Array ()]) p Ublic bool|array Insert (Array|object $a [, array $options = Array ()]) public Array[mongocommandcursor] Parallelcollect  Ionscan (int $num _cursors) public bool|array remove ([Array $criteria = Array () [, Array $options = Array ()]]) public Mixed Save (Array|object $a [, array $options = Array ()]) public bool Setreadpreference (string $read _preference [, a Rray $tags]) public bool Setslaveokay ([bool $ok = true]) public bool SetwriteconcErn (mixed $w [, int $wtimeout]) static protected string toindexstring (mixed $keys) public string __tostring (void Public bool|array Update (array $criteria, array $new _object [, Array $options = Array ()]) is public array validate ([ BOOL $scan _data = FALSE])}

It can be found that many of the methods provided by Mongocollection are similar to the methods we used to manipulate the data through the Mongo.exe process. You can refer to this (http://blog.csdn.net/hsd2012/article/details/51285831) by Mongo.exe process operation data.
Now, let's look at the data in the local MongoDB first.
We can see that there is a lot of data in the student collection in the school database, as shown in the following figure:

now I'm going to retrieve all the data from the stu_id between 15 and 22.
At the command prompt, we can do the following:

In the PHP program, we can do the following

Linked server
$m = new Mongoclient ();
Select a database
$db = $m->school;
Select a collection (The Mongo "set" corresponds to the "table" of the relational database)
$collection = $db->student;

$fruitQuery = Array (' stu_id ' => array (' $gte ' =>15, ' $lte ' =>22)); Set query conditions
$field =array (' _id ' =>0);//Set display field

$res = $collection->find ($fruitQuery, $field);

foreach ($res as $stu) {
    var_dump ($stu);
}

The way to find out the two types of data manipulation is similar. Just because you can't use JSON data directly in PHP, such as {name: "John"}, you can use an array to manipulate it. Add, modify, and delete MongoDB data Add Data

Linked server
$m = new Mongoclient ();
Select a database
$db = $m->school;
Select a collection (The Mongo "set" corresponds to the "table" of the relational database)
$collection = $db->student;

$data =array ("Stu_name" => "Lee 1", "Set" =>1, "class_id" =>5, "hobby" =>array ("Football", "basketball"));

$res = $collection->insert ($data);
Var_dump ($res);

Modifying Data

To modify the data in the collection student, the program is as follows:

Linked server
$m = new Mongoclient ();
Select a database
$db = $m->school;
Select a collection (The Mongo "set" corresponds to the "table" of the relational database)
$collection = $db->student;

STU_ID 9 of the student name to "Xiao Li"
$where =array (' stu_id ' =>9);
$set =array (' $set ' =>array (' class_name ' =>3, ' stu_name ' => ' Xiao Li '));
$options =array (' Upsert ' =>0, ' multiple ' =>1);

$rs = $collection->update ($where, $set, $options);
Var_dump ($RS);

$res = $collection->findone ($where);

Var_dump ($res);

Delete Data

Delete Data Use the Remove method, and now start to delete the data stu_id 9
The following diagram of the code:

Linked server
$m = new Mongoclient ();
Select a database
$db = $m->school;
Select a collection (The Mongo "set" corresponds to the "table" of the relational database)
$collection = $db->student;
$where =array (' stu_id ' =>9);
$rs = $collection->remove ($where);
Var_dump ($RS);
$res = $collection->findone ($where);
Var_dump ($res);

The effect is as follows:
Summary

Through PHP operation MongoDB Data method, can find, in fact, mostly and through Mongo.exe operation data is similar.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.