PHP using MongoDB

Source: Internet
Author: User

I. Installing the MONGODB PHP extension

wget http://pecl.php.net/get/mongo-1.2.7.tgz//Download Expansion pack
Tar zxvf mongo-1.2.7.tgz
CD mongo-1.2.7
/usr/local/php/bin/phpize
./configure-with-php-config=/usr/local/php/bin/php-config
Make

Make install

Note: When in Ubuntu environment, need root permission, need to add sudo, so sudo makes && make install will report error, should be sudo makes && sudo make install is OK, because make install also needs root permission.

Second, Mongodb's crud API

1. Connect MongoDB to get the collection

$conn = new Mongoclient ("mongodb://127.0.0.1:27017");
$db = $conn->mydb;
$collection = $db->user;

2.Insert operation

$u 1 = array (' ID ' =>216, ' name ' = ' wfm11 ', ' age ' =>121, ' addr ' = ' 2beijing ');
$result = $collection->insert ($u 1);
Echo ' New user u1: '. $u 1[' _id ']. ' <br> ';

3.Update operation

$re = $collection->update ($where = array (' ID ' =>1), Array ('set '=>array (' id ' =>1, ' name ' = > ' AAA ', ' addr ' = ' Hangzhou '));

4.Select operation

$cursor = $collection,find ()->snapshot ();
foreach ($cursor as $id = = $value) {
echo $id. ': '. $value [' id ']. ' ---> '. $value [' name '];
Var_dump ($value);
}

$cursor = $collection, find (Array (' ID ' =>array (' $gt ' =>0, ' $lte ' =>21 ));
while ($cursor->hasnext ()) {
Var_dump ($cursor->getnext ());
}

$doc = $collection-FindOne ();
Var_dump ($doc);

5.count operation

Echo ' Count: '. $collection, COUNT (). ' <br> ';
Echo ' id=1 count '. $collection, COUNT (array (' ID ' =>1)). ' <br> ';

6.remove operation

$re = $collectionRemove (array (' ID ' =>269));

7. Add an index, specify the collation

Add index on name (ASC), age (DESC)
$collection-ensureindex (Array ("name" =-1, "age" =>1));

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.