PHP Database Operation MongoDB Usage

Source: Internet
Author: User
Tags php database relational database table
This article mainly introduced the PHP database operation MongoDB Usage, combined with the case form more detailed analysis of MongoDB function, installation, basic commands, use methods and related considerations, the need for friends can refer to the next

Specific as follows:

Traditional database, we want to manipulate database data to write a large number of SQL statements, and in the storage of irregular data, the traditional relational database table when the processing of the different fields also appear somewhat weak, Mongo came into being, and the wide application of AJAX technology, JSON format widely accepted, It also makes MONGO closer to developers.

MONGO Introduction and Application Scenario

MongoDB is a document-oriented, non-relational database (NoSQL) that is stored in JSON format. Mongo DB is a good implementation of object-oriented thinking (Oo idea), in Mongo db each record is a document object. The biggest advantage of Mongo DB is that all data persistence requires no developers to write SQL statements manually, and it is easy to invoke methods to implement CRUD operations.

MONGO can be used in the following scenarios:

Store large, low-value data
JSON and Object type data
Site cache Data
Comments, sub-comment classes have explicit dependency data
Multi-server data, its built-in MapReduce is easy to realistically traverse globally.

Installing and Using MongoDB

We can download to its latest stable version on the official website https://www.mongodb.org/, MONGO is the official already compiles, the decompression can use its command in the bin directory.

First configure the mongo.conf file before use

Port=xxxxx         //Represents the port number and defaults to 27017 dbpath=/usr/local/mongodb/db    //database path if not specified logpath=/usr/local/mongodb/logs/ Mongodb.log//log path Logappend=true        //log files are automatically accumulated instead of overwriting fork=ture//         created in daemon mode

Database and data tables can be directly created, that is, without switching, direct use, when used to create, MONGO can also directly write JS script, can run directly, MONGO if you do not specify _id field, MONGO will automatically add one.

Various commands of the MONGO

MONGO's commands are the essence, and these very complex commands are set together, making MONGO's queries more brilliant and efficient. Each table in the MONGO is called a Collection (collection), using commands similar to MySQL, to switch to the database directly for each collection operation. Its command consists of the method (Func ()), the body of the query (written in {}), and the operator (starting with $).

Basic commands

Show DBS        //View database Use dbname        //Switch to Database Db.createcollection (' collection ')  //Create data Table Db.collection.drop ()     //Remove Data Sheet db.dropdatabase ()      //Delete database Db.collection.insert ({data})   //Insert Data Db.collection.find ()     // Show all contents in Datasheet

Query body

{Key.attr.attr:value}          Common type {key:{$ne | $gt | $gte | $lt | $lte | $in | $nin | $all: Value}}   //key satisfies the value of $oper value {$or | $and | $not | $nor: [{key1:{$gt: value}},{key2:{$ne: Value}}]}//Use $oper to qualify the Key1,key2 condition {key:{$mod {8,2}}}/           /To take out key to 8 with a value of 2. {key:{$exist: 1}}           Remove the value that exists in the key column. {key:{$type: string| double| array| date| Object| Boolean| ...} Query column {key:{$regex:/pattern/}}//         through regular queries, less efficient {$where: ' this.attr.express ... '}       //directly with a where statement , the binary to JS operation, slower

Find () Method enhancements

Db.collection.find (query,{to remove column: 1, unwanted column: 0})  db.collection.find (query). Skip (number of skipped rows). Limit (number of restricted information); Db.collection.find (query). Explain ()   ///Same as the MySQL explanatory statement. Db.collection.remove (Query,[justone])//If you do not specify query, delete all; [Justone] The default is false means query to multiple, but only one is deleted.

UPDATE statement

Db.collection.update (Query,{key:newvalue})//Note: The new value overwrites the old value, that is, the data is left only for the keydb.collection.update defined in the statement (query,{$set: {key: NewValue}, $unset: {key:value}, $rename: {key:value}, $inc: {Key:value}, ....},{multi:true,  //change all eligible, Default is False upsert:true  //Not added, default is false})

Cursor

var cursorname=db.collection.fund (query,...) [. Skip (num). Limit (num)]//Create cursor Cursorname.hasnext ()            ///Determine if there is a next Printjson (Cursorname.next ())          // The next pointing value of the output cursor Cursorname.foreach (function (OBJ) {process OBJ})      //traversal operation cursor

Index

Db.collection.getIndexes ()     //View index Db.collection.ensureIndex ({key:1/-1[,key.attr:1/-1]},{unique:1 (whether unique)},{ Sparse:1 (non-empty)})//Add positive/Reverse index Db.collection.dropIndex ({KEY:1/2})   //Delete index Db.collection.reIndex ()   // Rebuilding uses a lot of cluttered indexes.

Mapreduce

MapReduce is a very powerful traversal operation tool built into MONGO that uses it to implement its map and reduce two functions

Db.runcommand ({  mapreduce:collection,    //data table to manipulate  map:function () {Emit (Key1,key2)},//Data mapping for Key1 and Key2  reduce:function (key,value) {},  //operation on key value and data group value out  : <output>,  query: <document> ,  sort: <document>,  limit: <number>,  finalize: <function>,  scope: <document  Jsmode: <boolean>,  verbose: <boolean>})

More detailed commands can be found in MONGO's Chinese community http://docs.mongoing.com/manual-zh/.

MONGO user, data import Export and cluster

User Management

MongoDB does not turn on authorization by default. You can turn on authorization by adding the--auth or--keyfile option when the server is turned on. Use the Security.authorization or security.keyfile settings if you are using a configuration file.

MONGODB provides its own role, and each role provides a clear role for a common use case. Roles such as read, ReadWrite, dbAdmin, and Root. We manage users by creating users, creating roles, assigning/reclaiming different roles for users.

When you add a role, you add an administrator role in the Admin database and then use the Administrator role to add different roles to each library.

Use admin (Switch to admin database, operation on this library) Db.createuser ({User: "username", pwd: "Password", roles: [  {  role: " Useradminanydatabase ",  DB:" admin "  }]}) use Database;db.auth (' username ', ' passwd '), after login with Super Admin user, The entire MONGO database is accessible.

Data Import Export

We use MONGO's own tools for import and export, in the Mongo/bin directory, it is best to export CSV format, easy to exchange data.

./mongoexport-d dataname-c tablename-f key1,key2-q ' query '-o ainname--csv//export data, default to JSON format
./mongoimport-d dataname-c tablename--type json--file./path//Import data, default to JSON format

MONGO DB cluster

1. Add options when opening Mongod--replset replname;

2. On the MONGO client, connect to the previous Mongod process, go to the admin database, and then declare the mongoconf variable:

Use Admin;var rsconf={_id: ' Replname ', members[{_id:0,host: ' xxx '},{_id:1,host: ' Xxy '}];

3. With Rs.initiatee (rsconf), to initialize the cluster, MONGO will automatically set the ID number to primary, and the other Mongod process to secondary.

4. Connect the secondary process, using the Slaveok () function, to initialize the process from.

Working with MONGO database in PHP

Let's add the MONGO extension to PHP first (see: http://www.jb51.net/article/96829.htm). Then we can use the MONGO class library in the script.

Unlike other class libraries, there is only one core class, and MONGO has four classes, namely:

The MONGO class , the base class, has a connection, closes the connection, and operates on the global database.
MongoDB class , mail MONGO class is obtained through the Selectdb () method, which has a table-level operation method.
The mongocollection class , typically instantiated by mongo->dbname->collection or directly with MongoDB classes and database names, has basic operations on the data.
The Mongocursor class , obtained by mongocollection through the Find () method, has a normal cursor traversal operation.

The following is a typical MONGO operation:

$mongo =new MONGO (); $mongo->connect (' host ', port); $collection = $mongo->dbname->collection; $cursor =$ Collection->find (); $cursor->operate (); $mongo->close ();

Related recommendations:

PHP under the MONGODB Connection remote database detailed and case

Pecl Way to install php-mongodb Extension steps

PHP+MONGODB database Operation steps

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.