Home >Backend Development >PHP Tutorial >PHP operation MongoDB configuration and study notes_PHP tutorial

PHP operation MongoDB configuration and study notes_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:11:36913browse

Friends who need PHP operation MongoDB configuration and study notes can refer to it. Mongo mainly solves the problem of access efficiency of massive data. According to official documents, when the data volume reaches more than 50GB, Mongo's database access speed is more than 10 times that of MySQL

2. Installation (windows only)
Go to the official website to download the corresponding package
Extract it to d:mongodb
Create d:mongodbdata to place the data file

3. Run mongodb
There are some executable files under d:mongodbbin, among which mongod. exe is the server side and mongo.exe is the client side.
Run cmd, enter
d:mongodbbin>mongod.exe -dbpath d:mongodbdata
The server started successfully

4, let php support MongoDB
Download php_mongo.dll, pay attention to the version , php5.3.x should support v9 (some old information tells apache to download v6. In fact, you need to check phpinfo and download the corresponding version);
Modify php.ini and add extension = php_mongo.dll;
Restart apache.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444634.htmlTechArticleFriends in need of PHP operation MongoDB configuration and study notes can refer to it. Mongo mainly solves the problem of access efficiency of massive data. According to official documents, when the data volume reaches more than 50GB...
The code is as follows Copy code

/**
* PHP operation MongoDB study notes
* February 23, 2011
* Original author: xiaocai
*/

//******************************
//* * Connect to MongoDB database server
//******************************

//Format=>("mongodb ://username:password@address:port/default specified database", parameters)
$conn = new Mongo();
//can be abbreviated as
//$conn=new Mongo() ; //$conn=new Mongo("xiaocai.loc:10086") ; "xiaocai.loc",array("persist"=>"t"));          #Persistent connection
//$conn=new Mongo("mongodb://sa:123@localhost");                                                          Password
//$conn=new Mongo("mongodb://localhost:27017,localhost:27018"); #Connect multiple servers
//$conn=new Mongo("mongodb:/// tmp/mongo-27017.sock");​​​​​ #Domain socket
//$conn=new Mongo("mongodb://admin_miss:miss@localhost:27017/test",array('persist'=> 'p',"replicaSet"=>true)); #Complete



//******************** *****

//** Select database and table 

//****************************

$db=$conn->mydb;                                                                                                                                                                                                                                                                                    since $collection= $ db-& gt; colorn; #Select the collection (select the 'table')
// $ Collection = $ db-& gt; selectCollection ('colorn'); # conn->mydb->column;                                     #More concise writing

//Note:

// 1. Databases and collections do not need to be created in advance. If they do not exist, they will be created automatically.
// 2. Pay attention to typos, you may accidentally create a new database (confused with the original database).



//**** *********************

//** Insert document
//**************** **********

//**Insert data into the collection and return bool to determine whether the insertion is successful. **/
$array=array('column_name'=>'col'.rand(100,999),'column_exp'=>'xiaocai');
$ result=$collection->insert($array); #MongoDB will return a record identifier
var_dump($result) #Return: BOOL (TRUE)
#Insert results: {"_id": Objectid ("4D63552AD549A02C01000009"), "colorn_name": "colorn_exp": "xiaocai"}
#'_ ID' It is the primary key field, which is automatically added by MongoDB during insertion.

//**Safely insert data into the collection and return the insertion status (array). **/

$array=array('column_name'=>'col'.rand(100,999),' column_exp'=>'xiaocai2');
$result=$collection->insert($array,true); #Used to wait for MongoDB to complete the operation to determine whether it was successful. (Used when a large number of records are inserted This parameter will be more useful)
echo "New record ID:".$array['_id'];              #MongoDB will return a record ID "err"]=> NULL ["n"]=> int(0) ["ok"]=> float(1) }

//**Full syntax for insert **/
# insert(array $data,array('safe'=>false,'fsync'=>false,'timeout'=>10000))
# Parameter description: safe: default false, whether to write safely Enter; fsync: default false, whether to force insertion to be synchronized to disk; timeout: timeout (milliseconds)

//**The following two insertions are the same record (same _id) because their values ​​are the same**/

$collection->insert(array(' column_name'=>'xiaocai'));

$collection->insert(array('column_name'=>'xiaocai'));
#Avoid method, safe insertion
$collection- >insert(array('column_name'=>'xiaocai'),true);
try {
  $collection->insert(array('column_name'=>'xiaocai'),true) ;
}catch(MongoCursorException $e){
echo "Can't save the same person twice!n";
}
//Details: http://www.php.net /manual/zh/mongocollection.insert.php

 

//*************************

//** Update document                                         ************

//** Modification and update **/
$where=array('column_name'=>'col123 ');

$newdata=array('column_exp'=>'GGGGGGG','column_fid'=>444);

$result=$collection->update($where,array('$ set'=>$newdata)); #$set: Let a node equal the given value
/*
* Original data
* {"_id":ObjectId("4d635ba2d549a02801000003"),"column_name ":"col123","column_exp":"xiaocai"}
* was replaced by
* {"_id":ObjectId("4d635ba2d549a02801000003"),"column_name":"col123","column_exp": "GGGGGGGG","column_fid":444}
*/

//**Replacement update **/
$where=array('column_name'=>'col709');

$newdata=array('column_exp'=>'HHHHHHHHH','column_fid'=>123);

$result=$collection->update($where,$newdata);
/ *
* Original data
* {"_id":ObjectId("4d635ba2d549a02801000003"),"column_name":"col709","column_exp":"xiaocai"}
* Replaced with
* {"_id":ObjectId("4d635ba2d549a02801000003"),"column_exp":"HHHHHHHHH","column_fid":123}
*/

//**Batch update **/
$where=array('column_name'=>'col');

$newdata=array('column_exp'=>'multiple','91u'=>684435);

$result=$ collection->update($where,array('$set'=>$newdata),array('multiple'=>true));
/**
* All 'column_name'='col' are modified
*/

//**Automatic accumulation **/
$where=array('91u'=>684435);

$newdata=array('column_exp'=>'edit');

$ result=$collection->update($where,array('$set'=>$newdata,'$inc'=>array('91u'=>-5)));
/* *
* Update the data of 91u=684435, and decrement 91u by 5
* Note: Add -5 when 91u exists, and set 91u=-5 when it does not exist
*/

//**Update if matched, otherwise add **/
$c->update(
array("name" => "joe"),
array("username" => " joe312", "createdAt" => new MongoDate()),
array("upsert" => true) #up(date)(in)sert
);

/* *Delete node **/
$where=array('column_name'=>'col685');
$result=$collection->update($where,array('$unset'=> 'column_exp'));
/**
* Delete node column_exp
*/

/**Append new data to node **/
$coll->update(
array('b'= >1),
array('$push'=>array('a'=>'wow')) #Append new data to node a
);
# If the corresponding node is If the array does not exist, add a new value to it; if it does not exist, create the array and append a value to the array;
# If the node is not an array, return an error.
# Original record: array('a'=>array(0=>'haha'),'b'=>1)
# New record is: array('a'=> array(0=>'haha',1=>'wow'),'b'=>1)
# $pushAll is similar to $push, except that multiple values ​​will be appended to a node at one time

/**Judgment Update **/
$coll->update(
array('b'=>1),
array('$addToSet'=>array( 'a'=>'wow'))
);
# If there is no certain value in the array at this stage, add it
# Let the record structure be array('a'=>array (0=>'haha'),'b'=>1)
# If there is already wow in node a, then no new one will be added.
# If not, it will Add a new item to this node - wow.

/**Delete the last element of an array node **/
$coll->update(
array('b'=>1),
array('$pop'=> array('a'=>1)) #Delete the last element of the a array node
);

/**Delete the first element of an array node **/
$coll->update(
array('b'=>1),
array('$pop'=>array('a'=>-1)) #Delete the first element of the a array node
);

/**Delete elements of an array node **/
$coll->update(
array('b'=>1),
array('$pull'= >array('a'=>'haha'))
)
# If the node is an array, delete the sub-item whose value is value. If it is not an array, an error will be returned.
# The original record is: array('a'=>array(0=>'haha',1=>'wow'),'b'=>1),
# Delete a The sub-item with value haha
# The result is: array('a'=>array(0=>'wow'),'b'=>1)
# $pullAll and $pull Similar, except that you can delete a group of records that meet the conditions.

# Note:
# 1. Pay attention to distinguish replacement update and modification update
# 2. Pay attention to distinguish data types such as array('91u'=>'684435') and array('91u '=>684435)
 
//*************************
//** Delete document 
//****************** ************

/** Delete **/
$collection->remove(array('column_name'=>'col399'));
// $collection->remove(); #Clear the collection
//$collection->drop(); */

$id = new MongoId("4d638ea1d549a02801000011");

$collection->remove(array('_id'=>(object)$id));
/*
* *
* Use the following method to match {"_id":ObjectId("4d638ea1d549a02801000011")}, the same for query and update
* $id = new MongoId("4d638ea1d549a02801000011");
* array ('_id'=>(object)$id)
* *
*/


//********** ***************

//** Query Documents

//********************** ****

/**Query the number of records in the document **/
echo 'count:'.$collection->count()."
"; >count(array('type'=>'user'))."
";                                                      '=>array('$gt'=>50,'$lte'=>74)))."
"; #Greater than 50 and less than or equal to 74
echo 'count:'.$ collection->find()->limit(5)->skip(0)->count(true)."
";                                                                                                                                            because **
* Note: $gt means greater than, $gte means greater than or equal to, $lt means less than, $lte means less than or equal to, $ne means not equal to, $exists does not exist
*/

/**All documents in the collection **/
$cursor = $collection->find()->snapshot();
foreach ($cursor as $id => $value) {

echo "$id: "; var_dump($value); echo "
";

}
/**
* Note:
* After we do the find() operation and get the $cursor cursor, this cursor is still dynamic.
* In other words, after I find(), I get my cursor After the loop completes this period, if more qualified records are inserted into the collection, then these records will also be obtained by $cursor.
* If you want the result set to remain unchanged after obtaining $cursor, you need to do this:
* $cursor = $collection->find();
* $cursor->snapshot();#Get a snapshot!
* For details, please see http://www.bumao.com/index.php/2010/08/mongo_php_cursor.html
*/

/**Query a piece of data **/
$cursor = $collection->findOne();
/**

* Note: Snapshot(), fields() and other functions cannot be used after findOne() obtains the result set;

*/

/**age,type columns are not displayed * */
$cursor = $collection->find()->fields(array("age"=>false,"type"=>false));

/** Show only user column **/

$cursor = $collection->find()->fields(array("user"=>true));
/**

* It will make an error if I write like this: $cursor->fields(array("age"=>true,"type"=>false));

*/

/**(type,age nodes exist) and age!=0 and age<50 **/
$where=array('type'=>array('$exists'=>true),'age'=>array('$ne'= >0,'$lt'=>50,'$exists'=>true));
$cursor = $collection->find($where);

/** Get the result set by pagination **/
$cursor = $collection->find()->limit(5)->skip(0);

/**Sort **/

$cursor = $collection->find()->sort(array('age'=>-1,'type'=>1));                                                                                                                              Affects the sort order

/**Create index **/

$collection->ensureIndex(array('age' => 1,'type'=>-1)); means descending order - 1 means ascending order
$collection->ensureIndex(array('age' => 1,'type'=>-1),array('background'=>true)); #Index The creation is run in the background (the default is to run synchronously)

$collection->ensureIndex(array('age' => 1,'type'=>-1),array('unique'=> true));       #This index is unique


/**Get query results **/
$cursor = $collection->find();
$array=array();

foreach ($cursor as $id => $value) {

$array[]=$value;
}



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn