Operation of MongoDB Database in PHP

Source: Internet
Author: User
Tags findone mongodb server
This article mainly introduces the connection, addition, modification, query and deletion of the MongoDB database in PHP, the need for friends can refer to the following

Download PHP extension Mongon.mod.dll
Then php.ini add Extension=php_mongo.dll
Finally Phpinfo () found


Table tag PHP has its own MONGO feature, you can manipulate the following code (but you must have a MongoDB server installed)

First, connect the database

Create a database link using the following code

<?php$connection = new Mongo (mongodb://192.168.1.5:27017); Linking to the 192.168.1.5:27017//27017 port is the default. $connection = new Mongo ("example.com"); Link to remote host (default port) $connection = new Mongo ("example.com:65432"); A custom port Print_r ($connection->listdbs ()) linked to the remote host;//can print out a database array and see a few databases.?>


Say there is a database name called local, the total size of 1 bytes, he is empty. Seeing OK indicates a successful run.

Now you can use the $connection link to manipulate the database.

Select Database

Use the following code to select a database

<?php$db = $connection->dbname;? >

The database here is not necessarily an existing database, if the selected database does not exist, it will create a new database, so when selecting the database, be sure to fill in the correct database name
If the spelling is wrong, there is a good chance that you will create a new database

<?php$db = $connection->mybiglongdbname;//do something $db = $connection->mybiglongdbnme;//will now connect to the previous new database?>

Get a Collection

Gets a collection that has the same syntax format as the Select database

<?php$db = $connection->baz;//Select database $collection = $db->foobar;//Select Foobar Collection//or use a cleaner way $collection = $ Connection->baz->foobar;? >

Insert a document

Multidimensional arrays are basic units that can be stored in a database
A random document might be like this

<?php$doc = Array ("name" + "MongoDB",    "type" = "database",    "count" = 1,    "info" = = (object) Array ("x" = 203,    "y" = = 102),    "versions" = = Array ("0.9.7″," 0.9.8″, "0.9.9″)";? >

Note: You can nest arrays with objects, objects and documents are almost identical in MongoDB, you can call a document or object using $doc, but the info field is always an object instead of a document.
This constraint applies to all documents
Insert a document using Mongocollection::insert ()

<?php$m = new Mongo (), $collection = $m->foo->bar; $collection->insert ($doc);? >

MongoDB Insert (), Save (), the main difference is: if there is a primary key, insert () do not operate, and save () change the original content as new content.
Existing data: {_id:1, ' name ': ' N1 '}
Insert ({_id:1, "name": "N2"}) will prompt for an error
Save ({_id:1, "name": "N2"}) will change the N1 to N2.

Querying documents using Mongocollection::findone ()

To prove that the data in the above code has been inserted into the database, we perform a simple findOne () operation to get the first document data in the collection, which returns only one document data,
This method is suitable for matching only one document at the time of your query statement, or you only care about the first piece of data

<?php$obj = $collection->findone (); Var_dump ($obj);? >

You will see the following results

Array (5) {  ["_id"]=>  object (MongoId) #6 (0) {  }  ["Name"]  string (7) "MongoDB"  ["type"]= >  String (8) "Database"  ["Count"]=>  int (1)  ["Info"]=>  Array (2) {    ["x"]=>    Int (203)    ["Y"]=>    Int (102)  }  ["Versions"]  Array (3) {    [0]=>    string (5) "0.9.7″    [1]= >    String (5) "0.9.8″    [2]=>    string (5)" 0.9.9″  }}

Note that the _id field is automatically loaded on the document, and the MongoDB storage element begins with _ and $ for internal use.

Add more Documents

To do something more interesting, we add more simple documents to the collection, these documents are

<?phparray ("i" = = value);? >

We can use loops to insert data fairly efficiently

<?phpfor ($i =0; $i <100; $i + +) {    $collection->insert (Array ("I" = $i)); >

Note: We can insert different fields in the same character set, which means MongoDB has a very free storage mode

Calculate the number of documents in a collection

Now that we've inserted 101 documents (we've inserted 100 in a loop, we've inserted one before), we can use count () to see if our data is all plugged in.

<?phpecho $collection->count ();? >

This code will print out 101

Mongocollection::count () can also query field data

Use cursors to get all the documents in the collection

To get all the documents in the collection, we can use the Mongocollection::find () method, and the Find () method returns a Mongocursor object that allows us to repeat the document that the query matches

<?php$cursor = $collection->find (); foreach ($cursor as $id = + $value) {    echo "$id:";    Var_dump ($value);}? >

This will print out the 101 documents in the collection, $id is the _id field in the document, $value the document itself

Set a standard for queries
We can get a subset of the documents in the collection through the Find () method, for example, if we want to query the document for the I field 71 in the collection, we can use the following methods

<?php$query = Array ("I" = +), $cursor = $collection->find ($query), while ($cursor->hasnext ()) {    var_d UMP ($cursor->getnext ());}? >

We will print the following data

Array (2) {  ["_id"]=>  object (MongoId) #6 (0) {  }  ["I"]=>  int () [  "_ns"]=>  " Testcollection "}

Set a range for a query

We can create a query statement from find () to get a subset of the set, for example, if we get all the "I" >50 documents, we can use the following code

<?php$query = Array ("i" = = Array (' $GT ' =>50)); Note that the single quotation marks on either side of ' $gt ' $cursor = $coll->find ($query), while ($cursor->hasnext ()) {    var_dump ($cursor->getnext () );}? >

We can also get data between the < I <= 30

<?php$query = Array ("i" = = Array ("\ $gt" = "\ $lte" =)); $cursor = $coll->find ($query); while ($ Cursor->hasnext ()) {    var_dump ($cursor->getnext ());}? >

We are very easy to miss the $ dollar sign, you can also choose your custom symbol instead of the dollar sign, choose a symbol that will not appear in your build, such as ":", add such a sentence in the php.ini

Mongo.cmd = ":"

Then the code above can be replaced

<?php$query = Array ("i" = = Array (": GT" = +, ": LTE" = 30)); >

Of course you can also use the Ini_set ("Mongo.cmd", ":") method to change

Create an index

MongoDB supports indexes and can be easily added to a collection, as long as you specify a field as an index, and you can also specify a positive ordinal index (1) and a reverse index (-1)
The following code creates an index for I

<?php$coll->ensureindex (Array ("I" = 1));  An index $coll->ensureindex (array ("I" = 1, "j" = 1) was created on "I");//The reverse index created on "I" creates a positive-order index on "J"?>

A complete and simple example

This example shows how to link a mongodb database, how to select a database, how to insert data, how to query data, and close a database link

<?php//link $m = new Mongo ();//Select a database $db = $m->comedy; $collection = $db->cartoons;//Add an element $obj = Array ("title" =& Gt "Calvin and Hobbes", "Author" = "Bill Watterson"), $collection->insert ($obj);//Modify $newdata = Array (' $set ' = arr Ay ("title" = "Calvin and Hobbes"), $collection->update ("Author" = "Caleng"), $newdata);//delete $ Collection->remove (Array (' author ' = ' Caleng '), Array ("justone" = True));//Add another element, using a different format $obj = Array (" Title "=" = "XKCD", "online" = true); $collection->insert ($obj);//Query all collections $cursor = $collection->find ();// Repeated display of the result foreach ($cursor as $obj) {    echo $obj ["title"]. "\ n";} Close link $m->close ();? >

The output result is

Calvin and HOBBESXKCD

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.