Application development of PHP based on MongoDB

Source: Internet
Author: User
Tags create index mongodb mongodb server prev sessions
  First, connect the database hostConnect local host, port is 27017: $connection = new Mongo ();
Connect remote host, port is default port: $connection = new Mongo ("192.168.2.1");
Connect the remote host port to the specified port: $connection = new Mongo ("192.168.2.1:65432");
Select the database, and if the specified database does not exist, a new database will be created automatically, with 2 methods: $db = $connection->selectdb (' dbname '); or $db = $connection->dbname;
Select a collection (collection), similar to a table in a relational database, with 2 methods: $collection = $db->selectcollection (' People '); or $collection = $db->people;
ii. inserting new documents (document)The collection object is used to perform information management, for example, to store a message about someone, which can be encoded as follows: $person = Array (' name ' => ' Cesar Rodas ', ' email ' => ' crodas@php.net ') , ' Address ' => Array (Array (' Country ' => ' PY ', ' Zip ' => ' 2160 ', ' Address1 ' => ' foo bar '), AR Ray (' Country ' => ' PY ', ' Zip ' => ' 2161 ', ' Address1 ' => ' foo bar bar foo '), ' sessions ' => 0,) ;
$safe _insert = true; $collection->insert ($person, $safe _insert); $person _identifier = $person [' _id '];
Where: The $safe _insert parameter is used to wait for MongoDB to complete the operation in order to determine success, the default value is False, and it is useful to use this parameter when there is a large number of records inserted. When you insert a new document, MongoDB returns a record identity.
Third, update the documentFor example, update the personal information that has been created above, add the Sessions property value, add the Address2 attribute to the 1th address, and remove the 2nd address, as follows: First, define a filter (filters) Tell MongoDB to update a specified document $filter = array (' email ' => ' crodas@php.net '); $new _document = Array (' $inc ' => Array (' Sessions ' => 1), ' $set ' => array (' Address.0.address2 ' => "Some Foobar Street ',), ' $unset ' => array (' Address.1 ' => 1),); $options [' multiple '] = false; $collection->update ($filter, $new _document, $options);
MongoDB also supports batch updates, similar to relational databases, where you can update all documents for a given condition, and if you want to do so, you need to set the multiple value of the options to true.
Four, inquires the documentDefines a conditional filter that conforms to a given standard, and obtains the document by using the query selector. For example, through e-mail address to obtain information: $filter = array (' email ' => ' crodas@php.net '); $cursor = $collection->find ($filter); foreach ($cursor as $user) {var_dump ($user);}
For example, to obtain information sessions greater than 10: $filter = Array (' Sessions ' => Array (' $GT ' => 10)); $cursor = $collection->find ($filter);
For example, get information that does not have the Sessions property set: $filter = Array (' Sessions ' => Array (' $exists ' => false)); $cursor = $collection->find ($filter);
For example, obtain information about the address in PY and sessions greater than 15: $filter = Array (' address.country ' => ' PY ', ' Sessions ' => Array (' $GT ' => 10)); $cursor = $collection->find ($filter);
One important detail to note is that the query is executed only when the result is needed, and in the 1th example, the query is executed when the Foreach loop begins. This is a useful feature because it allows you to retrieve the result by adding an option to the cursor (cursor), just before the query is executed, after the query is defined. For example, you can set options to perform pagination, or get a specified number of matching documents. $total = $cursor->total (); $cursor->limit (->skip) (40); foreach ($cursor as $user) {}
v. Get the document ClusteringMongoDB supports clustering of results, similar to relational databases, and can use clustering such as COUNT,DISTINCT and group operations. Clustering queries return arrays (array), not entire document objects. The grouping operation allows you to define MONGODB server-side features written in JavaScript that perform grouping properties. This is more flexible because it can perform many types of operations with grouped values, but it is still difficult compared to simple grouping operations like sum (), AVG (), such as SQL execution. The following example shows how to obtain a country's address list, and the number of times the country that matches the address appears: $countries = $collection->distinct ("Address.country"); $result = $collection->group (Array ("Address.country" => True),
Array ("sum" => 0),
"Function (obj, prev) {prev.sum = 1;}",
Array ("Session" => Array (' $GT ' => 10))
);
VI. Delete DocumentDeleting a document is similar to getting or updating a document. $filter = Array (' field ' => ' foo '); $collection->remove ($filter);
Note that all eligible documents are deleted by default, and if you want to delete only the 1th document that matches the criteria, assign the second argument to the Remove function to true.
Vii. Index SupportThere is a very important feature that makes the decision to choose MongoDB instead of selecting other similar document-oriented databases, which is supported by indexes that are similar to the table indexes of relational databases, and not all document-oriented databases provide built-in indexing support. Using the MongoDB CREATE index feature avoids operating in all documents during a query, like using indexes in relational databases to avoid full table queries. This speeds up queries that relate to qualifying documents that involve indexed properties. For example, if you want to establish a unique index on an e-mail address property, as follows: $collection->ensureindex (' email ' => 1), Array (' Unique ' => true, ' Background ' => true));
The 1th array parameter describes all the properties that will be indexed, and can be 1 or more properties. By default, the creation of an index is a synchronous operation, so if the number of documents is large, it would be a good idea to put the creation of the index in the background, as demonstrated in the example above. The index of only one attribute may not be sufficient, and the following example shows how to speed up the query by defining an index on 2 properties. $collection->ensureindex (Array (' Address.country ' => 1, ' Sessions ' => 1), array (' background ' => true));
The value of each index defines the order of the indexes: 1 for descending (descending),-1 for Ascending (ascending) index order is useful in query optimization with sort options, as in the following example: $filter = Array (' Address.country ' =& Gt ' PY ',); $cursor = $collection->find ($filter)->order (Array (' Sessions ' =>-1));
$collection->ensureindex ( array (' Address.country ' => 1, ' Sessions ' =>-1),  array (' background ' = > True));
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.