PHP MongoDB database connection, add, modify, query, delete and other examples of operations _mongodb

Source: Internet
Author: User
Tags arrays character set findone mongodb mongodb server php mongodb

PHP extension mongon.mod.dll Download http://cn.php.net/manual/en/mongo.installation.php#mongo.installation.windows
Then php.ini add Extension=php_mongo.dll
Finally Phpinfo () find


The table label PHP has its own MONGO function, you can operate the following code (but you must have the installation MongoDB server)

One, the connection database

Create a database link using the following code

Copy Code code as follows:
<?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"); Custom ports linked to remote hosts
Print_r ($connection->listdbs ());//can print out an array of databases to see how many databases there are.

?>

As shown in figure:


There is a database named local, the total size of 1 bytes, he is empty. See OK indicates successful operation.

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

Select Database

Use the following code to select a database

Copy Code code as follows:
<?php
$db = $connection->dbname;
?>

The database here is not necessarily an existing database, if the selected database does not exist, you will create a new database, so when you select the database, be sure to fill in the correct database name
If you spell incorrectly, you will probably create a new database

Copy Code code as follows:
<?php
$db = $connection->mybiglongdbname;
Do some things
$db = $connection->mybiglongdbnme;
You will now connect to a new database
?>

Gets a collection

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

Copy Code code as follows:
<?php
$db = $connection->baz;//Select database
$collection = $db->foobar;//Select Foobar Collection
Or use a more concise approach.
$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

Copy Code code as follows:
<?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 and objects, objects and documents are almost the same in MongoDB, you can use $doc to invoke a document or object, but the info field is always an object rather than a document,
This constraint applies to all documents
Insert a document using Mongocollection::insert ()

Copy Code code as follows:
<?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 () does not operate, and save () changes the original content is new content.
Presence data: {_id:1, ' name ': ' N1 '}
Insert ({_id:1, "name": "N2"}) prompts for an error
Save ({_id:1, "name": "N2"}) will change N1 to N2.

Querying documents using Mongocollection::findone ()

In order to prove that the above code data has been inserted into the database, we do a simple findone () operation to get the first document data in the collection, this method returns only one document data,
This approach applies to matching only one document at the time of your query, or you only care about the first piece of data

Copy Code code as follows:
<?php
$obj = $collection->findone ();
Var_dump ($obj);
?>

You will see the following results

Copy Code code as follows:
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 that the MongoDB storage element starts with _ and $ for internal use

Add more Documents

To do something more interesting, we add more simple documents to the collection, which are as follows

Copy Code code as follows:
<?php
Array ("I" => value);
?>

We can use loops to insert data fairly efficiently.
Copy Code code as follows:
<?php
For ($i =0 $i <100; $i + +) {
$collection->insert (Array ("I" => $i));
}
?>

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

Count 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 plugged in.

Copy Code code as follows:

<?php
echo $collection->count ();
?>

This code will print out 101

Mongocollection::count () can also query field data

Use cursors to get all 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.

Copy Code code as follows:
<?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 is the document itself

Set a standard for a query
we can get a subset of the documents in the collection by using the Find () method, for example, to query the document with the I field 71 in the collection, we can use the following methods

Copy Code code as follows:
<?php
$query = Array ("I" => 71);
$cursor = $collection->find ($query);
while ($cursor->hasnext ()) {
Var_dump ($cursor->getnext ());
}
?>

We will print the following data
Copy Code code as follows:
Array (2) {
["_id"]=>
Object (mongoid) #6 (0) {
}
["I"]=>
Int (71)
["_ns"]=>
"Testcollection"
}

Set a range for a query

We can create a query statement by using Find () to get a subset of the collection, for example, if we get all the "I" >50 documents, we can use the following code

Copy Code code as follows:
<?php
$query = Array ("I" => Array (' $GT ' =>50)); Note the single quotes on both sides of the ' $gt '
$cursor = $coll->find ($query);
while ($cursor->hasnext ()) {
Var_dump ($cursor->getnext ());
}
?>

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

Copy Code code as follows:
<?php
$query = Array ("I" => array ("\ $gt" =>, "\ $lte" => 30));
$cursor = $coll->find ($query);
while ($cursor->hasnext ()) {
Var_dump ($cursor->getnext ());
}
?>

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

Copy Code code as follows:
Mongo.cmd = ":"

Then the code above can be replaced with
Copy Code code as follows:
<?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 indexing and can easily be added to a set, you just specify that a field is indexed, and you can also specify a positive sequence index (1) and a descending index (-1)
The following code creates an index for I

Copy Code code as follows:
<?php
$coll->ensureindex (Array ("I" => 1)); An index was created on "I"
$coll->ensureindex (Array ("I" =>-1, "J" => 1))//Reverse index created on "I" creates a positive index on "J"
?>

A complete and simple example

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

Copy Code code as follows:
<?php
Link
$m = new Mongo ();

Select a database
$db = $m->comedy;
$collection = $db->cartoons;

Add an Element
$obj = Array ("title" => "Calvin and Hobbes", "Author" => "Bill Watterson");
$collection->insert ($obj);

Modify
$newdata = Array (' $set ' => Array ("title" => "Calvin and Hobbes"));
$collection->update (Array ("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);

To query all collections
$cursor = $collection->find ();

Show results repeatedly
foreach ($cursor as $obj) {
echo $obj ["title"]. "\ n";
}

Close link
$m->close ();
?>


Output results are
Copy Code code as follows:
Calvin and Hobbes
XKCD

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.