Install using MongoDB database in PHP _mongodb

Source: Internet
Author: User
Tags auth mongodb relational database table

In the traditional database, we have to manipulate the 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 different fields appears to be a bit weak, MONGO, and the wide application of AJAX technology, JSON format widely accepted, It also makes MONGO closer to developers.

MONGO Introduction and application Scenarios

MongoDB is a document-oriented, non-relational database (NoSQL) that is stored using JSON format. Mongo db is a good way to implement object-oriented thinking (OO), where each record in Mongo DB is a document object. The biggest advantage of Mongo DB is that all data persistence operations require no developer to manually write SQL statements, and the direct invocation of the method makes it easy to implement CRUD operations.

MONGO can be applied in the following scenarios:

Storage of large size, low value data
JSON and Object type data
Web Site cache Data
Comments, sub-comment classes have significant dependency data
Multi-server data, its built-in mapreduce is easy to realistically global traversal.

Install and use MongoDB

We can download the latest stable version of the official website https://www.mongodb.org/, MONGO is officially compiled, after decompression can use its command in the bin directory.

First configure mongo.conf files before use

Copy Code code as follows:
Port=xxxxx//Represents the port number and defaults to 27017 if not specified
DBPATH=/USR/LOCAL/MONGODB/DB//database path
Logpath=/usr/local/mongodb/logs/mongodb.log//log path
Logappend=true//log files automatically accumulate instead of overwriting
Fork=ture//created in daemon mode

Database and datasheet 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 the _id field is not specified, MONGO will automatically add one.

The various orders of MONGO

MONGO's command is the essence of these very complex commands assembled in a piece, making the MONGO query become gorgeous and efficient. Each table within the MONGO is called a collection (set), using commands similar to MySQL, and switching to a database directly to each collection operation. The command consists of a method (Func ()), a query body (written in {}), and an operator (starting with $).

Basic commands

Copy Code code as follows:
Show DBS//View Database
Use dbname//switch to Database
Db.createcollection (' collection ')//create Datasheet
Db.collection.drop ()//delete datasheet
Db.dropdatabase ()//delete database
Db.collection.insert ({data})//Insert Data
Db.collection.find ()//Display all contents in Datasheet

Query body

Copy Code code as follows:
{Key.attr.attr:value}//Common type
{key:{$ne | $gt | $gte | $lt | $lte | $in | $nin | $all: Value}}//key to meet the values of $oper value
{$or | $and | $not | $nor: [{key1:{$gt: value}},{key2:{$ne: Value}}]}///$oper Key1,key2 conditions at the same time
{key:{$mod {8,2}}}//Remove key to 8 with 2 value.
{key:{$exist: 1}}//Remove the value that exists for the key column.
{key:{$type: string| double| array| date| Object| Boolean| ...} Query for columns of type key
{key:{$regex:/pattern/}}//through regular queries, less efficient
{$where: ' this.attr.express ... '}///Direct use where statement, binary to JS operation, slower

The find () method enhances

Copy Code code as follows:
Db.collection.find (query,{to be removed: 1, unwanted column: 0})
Db.collection.find (query). Skip (number of rows skipped). Limit (Limit the number of information bars);
Db.collection.find (query). Explain ()///As explained in MySQL.
Db.collection.remove (Query,[justone])//If you do not specify query, delete all; [Justone] default to False means query to multiple, but delete only one.

UPDATE statement

Copy Code code as follows:
Db.collection.update (Query,{key:newvalue})//Note: The new value overwrites the old value, which means that the data is left with the key defined in the statement
Db.collection.update (Query,
{
$set: {Key:newvalue},
$unset: {Key:value},
$rename: {Key:value},
$inc: {Key:value},
......
},
{
Multi:true,//change all eligible, default to False
Upsert:true//No words just added, default to False
}
)

Cursor

Copy Code code as follows:
var cursorname=db.collection.fund (query,...) [. Skip (num). Limit (num)]//Create a cursor
Cursorname.hasnext ()//Determine if there is a next
Printjson (Cursorname.next ())//output cursor Next pointing value
Cursorname.foreach (function (obj) {process OBJ})//Traversal action cursor

Index

Copy Code code as follows:
Db.collection.getIndexes ()//View Index
Db.collection.ensureIndex ({key:1/-1[,key.attr:1/-1]},{unique:1 (unique)},{sparse:1 (not NULL)})//Add positive/Descending index
Db.collection.dropIndex ({KEY:1/2})//delete index
Db.collection.reIndex ()//reconstruction uses a lot of random indexes

Mapreduce

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

Copy Code code as follows:
Db.runcommand (
{
Mapreduce:collection,//data table to be manipulated
Map:function () {Emit (Key1,key2)},//Data map to Key1 and Key2
Reduce:function (Key,value) {},//action on key value and data group value
Out: <output>
Query: <document>,
Sort: <document>
Limit: <number>
Finalize: <function>
Scope: &LT;DOCUMENT&GT;
Jsmode: <boolean>
VERBOSE: <boolean>
}
)

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

MONGO user, data import Export and cluster

User Management

MongoDB does not open authorization by default. You can add--auth or--keyfile options when you turn on the server to turn on authorization. Use the Security.authorization or security.keyfile settings if you use a configuration file.

MongoDB provides a self-contained role, with each role providing a clear role for a common use case. such as read, ReadWrite, dbadmin, and root roles. We create users, create roles, and assign/recycle different roles for users to manage.

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

Copy Code code as follows:
Use admin; (Switch to admin database, operate on this library)
Db.createuser (
{
User: "username",
PWD: "Password",
Roles
[
{
Role: "Useradminanydatabase",
DB: "Admin"
}
]
}
)
Use database;
Db.auth (' username ', ' passwd '), access to the entire MONGO database when logged in by a Super Admin user.

Data Import Export

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

Copy Code code as follows:
./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 Database Cluster

Add options when opening Mongod--replset replname;
On the MONGO client connects to the previous Mongod process, enter the admin database, and then declare the mongoconf variable:

Use admin;
var rsconf={_id: ' Replname ', members[{_id:0,host: ' xxx '},{_id:1,host: ' Xxy '}]};
Using Rs.initiatee (rsconf) to initialize the cluster, MONGO automatically sets the ID number to primary, and the other Mongod process is secondary.

Connect the secondary process and use the Slaveok () function to initialize the process.
Operation MONGO Database in PHP
We first add MONGO extensions to PHP (see PHP under Linux). Then, we can use the MONGO class function library in the script.

Unlike other class libraries, which have only one core class, MONGO has four classes, respectively:

The MONGO class, the base class, has a connection, closes the connection, and operates on the global database.
MongoDB class, the Mail MONGO class is obtained by the Selectdb () method, and has the table-level operation method.
Mongocollection class, generally by mongo->dbname->collection or directly with the MongoDB class and database name instantiation, with the basic operation of the data.
The Mongocursor class, obtained by the mongocollection through the Find () method, has a normal cursor traversal operation.
The following is a typical MONGO operation:

Copy Code code as follows:
$mongo =new MONGO ();
$mongo->connect (' host ', port);
$collection = $mongo->dbname->collection;
$cursor = $collection->find ();
$cursor->operate ();
$mongo->close ();

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.