PHP Operation MongoDB

Source: Internet
Author: User
Tags findone mongodb server

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 () found

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


Link 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"); Linking to a remote host (default port)
$connection = new Mongo ("example.com:65432"); A custom port that is linked to a remote host
Print_r ($connection->listdbs ());//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 some things
$db = $connection->mybiglongdbnme;
A new database is now connected
?> Get a collection
Gets a collection that has the same syntax format as the Select Database <?php
$db = Select Database $connection->baz;//
$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
<?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 using Mongocollection::insert () to insert a document
<?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
<?php
Array ("i" = = value);
?> we can use loops to insert data fairly efficiently
<?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 MongoDB has a very free storage mode to 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.
<?php
echo $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 query
The document that is matched
<?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" = 71);
$cursor = $collection->find ($query);
while ($cursor->hasnext ()) {
Var_dump ($cursor->getnext ());
}
?>
We will print the following data
Array (2) {
["_id"]=>
Object (MongoId) #6 (0) {
}
["I"]=>
Int (71)
["_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 the single quotation marks on both sides 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" = 30));
$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 was created on "I"
$coll->ensureindex (Array ("I" = 1, "j" = 1));//Create a reverse index on "I" to create a positive sequence index on "J"
?> a simple sample.
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" = "Calvin and Hobbes", "Author" = "Bill Watterson");
$collection->insert ($obj);

Add another element, using a different format
$obj = Array ("title" = "XKCD", "online" = true);
$collection->insert ($obj);

Querying all the collections
$cursor = $collection->find ();

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

Close link
$m->close ();
The?> output results are
Calvin and Hobbes
XKCD

PHP Operation MongoDB

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.