PHP operations on mongodb

Source: Internet
Author: User
Tags findone mongoclient
Basic Tutorial: 1. Connect to the mongo database server. Syntax example :? Php $ connectionnewclientclient (); connect to the local database. The default port is 27017. That is, localhost: 27017 $ connectionnewclientclient (mongodb: example.com); connect to the remote database. The default port is 27017 $ connect.

Basic Tutorial: 1. Connect to the mongo database server. Syntax example :? Php $ connection = new clients client (); // connect to the local database. The default port is 27017. that is, localhost: 27017 $ connection = new clients client (mongodb: // example.com); // connect to the remote database. The default port is 27017 $ connect.

Basic Tutorial: 1. Connect to the mongo database server.

Syntax example:

 
2. connect to a database

Syntax example:

 
$ Db = $ connection-> dbname; // select a database named dbname?>
The database name does not need to be created beforehand. When you select it, mongodb can create a new database named dbname.

Note: Do not write the wrong database name. Otherwise, you will inadvertently generate a database, which will lead to database confusion.

The following program generates two databases due to spelling errors:

  
$connection = new MongoClient();
$ Db = $ connection-> mybiloglongdbname; // connect to a database
$ Db = $ connection-> mybiloglongdbanme; // connect to a database with different names
 ?>
3. connect to a database set

The syntax for getting a set and connecting to a database is the same.

Syntax example:

   
$connection = new MongoClient();
$ Db = $ connection-> baz; $ collection = $ db-> foobar; // select a set
// You can also directly select a database and a collection.
$collection = $connection->baz->foobar;
?>
A set is similar to a table in a relational database.
4. Insert a document

Join array is the most basic structure, which is saved to the set.

Some random "documents" can be:

    
$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 have nested arrays and objects. The driver usually saves an associated array as an object in a database.

A numeric index array is usually stored as an array based on the following conditions: the keyword starts from 0 and is uninterrupted. Or as an object

: The keyword of the array does not start from 0, and there is a break in the middle.

Insert this document. You can use this function to compile collection: insert ():

     
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$collection->insert($doc);?>
5. Search for a collection using collections collection: findOne ()

In order to search for the set of data, we have already stored the corresponding data in the database. We only need a simple method.

Collections collection: findOne () to get a unique document from the collection. This method applies to: only one data matching

Query data.

Instance:

      
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$document = $collection->findOne();
var_dump($document);
?>
The above instance output:
array(6) {["_id"]=>object(MongoId)#8 (1) {["$id"]=>string(24) "4e2995576803fab768000000"}["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"  }}
We noticed that the field "_ id" has been automatically added to the document, and "_ id" is the primary key field.

If no primary key field is defined in the document, the driver automatically adds one.

If you define your own _ id field, it must be unique to the entire set.

Example:

       
$connection = new MongoClient();
$db = $connection->datebase;
$db->foo->insert(array("_id"=>1));
// The following will throw an exception
$db->foo->insert(array("_id"=>1));
// The following is correct because it is in another collection
$db->bar->insert(array("_id"=>1));
?>
You can also pass the Array ("w" => 0) as the second element and choose to disable this behavior.

That is to say, the driver does not have to wait for the database to confirm the write, and does not have to throw a replication _ id exception.

6. add multiple documents

To let us do more interesting things, we will add many simple documents to the set.

These documents are just in this form of data array ("I" => value), and we can add them in a loop quite efficiently.

        
$connection = new MongoClient();
$collection = $connection->database->collectionName;
for($i=0;$i<100;$i++)
{
$collection->insert(array('i'=>$i, "field{$i}"=>$i*2));
}
?>
Note: We can insert documents with different keywords in the same set, which is why we call MongoDB a free mode.
7. count the number of documents in a collection

When we insert 101 documents into the collection, we can use the method of statistics collection: count () to count the number of documents:

         
$connection = new MongoClient();
$collection = $connection->database->collectionName;
echo $collection->count();
?>
Output result: 1018. Use Cursor to get all documents

To get all the documents in the set, we will use collections collection: find ().

The find () method returns an iterator cursor object, which allows us to iterate documents that meet our query conditions.

Query all documents and print them out.

          
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$cursor = $collection->find();
foreach($cursor as $id=>$value)
{
echo "$id:";
var_dump($value);
}
?>
All documents in the set can be printed.

$ Id I is the _ id field of the document, and $ value is the document itself.

9. Set the query standard. We can use a query statement to obtain a subset of the documents in the collection by using the method of getting collection: find.

For example, if you want to find the document with the "I" field value 71, we can do the following:

           
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$query = array('i'=71);
$cursor = $collection->find($query);
while($cursor->hasNext)
{
var_dump($cursor->getNext());
}
?>
Output:
array(2) {  ["_id"]=>  object(MongoId)#6 (0) {  }  ["i"]=>  int(71)  ["_ns"]=>  "testCollection"}
10. query a series of documents

We can query a series of documents from the collection.

For example, if you want to obtain all the documents from 'I> 50, we can write them as follows:

            
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$query = array("i"=>array('$gt'=>50));
$cursor = $coll->find($query);
while($cursor->hasNext())
{
var_dump($cursor->getNext());
}
?>
We can also query a range: 20
$connection = new MongoClient();
$collection = $connection->db->collectionName;

             
$query = array('i'=>array('$gt'=>20,"\$lte"=>30));
$cursor = $collection->find($query);

             
while($cursor->hasNext)
{
var_dump($cursor->getNext());
}
?>
$ Gt greater than; $ gte greater than or equal to; $ in range; $ it less than; $ lte less than or equal;
find( { qty: { $in: [ 5, 15 ] } } )

$ Ne: Query all data not equal to this element;

$ Nin: Query all data out of the scope

Note: $ characters under single quotes do not need to be escaped, but double quotes do need to be escaped.

11. Create an index

MongoDB supports indexes, and the indexes can be easily added to the collection.

To create an index, You need to define a field and direction: ascending (1) or descending (-1 ).

The following creates an index in ascending order on the 'I field:

              
$connection = new MongoClient();
$collection = $collection->database->collectionName();
$ Collection-> ensureIndex (array ("I" => 1); // create an index in the ascending order of 'I'
$ Collection-> ensureIndex (array ("I" =>-1, "j" => 1); // create a descending order on 'I, the index in the 'J' ascending order.
?>
As data grows, indexing becomes the key to good database read performance.
If you are not familiar with the index reading performance, you can refer to the documents related to indexing collection: ensureIndex () Indexing collection: ensureIndex.

Reference: http://www.php.net/manual/zh/mongo.tutorial.connecting.php

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.