Home > Article > Backend Development > PHP operation MongoDB study notes
/**
column
* PHP operation MongoDB study notes
*/
//***************************
//** Connect to MongoDB database **//
//***************************
//Format =>("mongodb://username:password @address:port/default specified database", parameters)
$conn = new Mongo();
//can be abbreviated as
//$c Mongo(); #Connect to local host, default port.
//$c Mongo(“172.21.15.69″); #Connect to remote host
//$c Mongo(“xiaocai.loc:10086″); #Connect to the remote host on the specified port
//$c Mongo("xiaocai.loc",array("replicaSet"=>true)); #Load balancing
//$c Mongo("xiaocai.loc",array("persist"=>"t")); #Persistent connection
//$c Mongo(“mongodb://sa:123@localhost”); #With username and password
//$c Mongo(“mongodb://localhost:27017,localhost:27018″); #Connect multiple servers
//$c Mongo("mongodb:///tmp/mongo-27017.sock"); #Domain socket
//$c Mongo("mongodb://admin_miss:miss@localhost:27017/test",array('persist'=>'p',"replicaSet"=>true)); #Complete
//Details: http://www.php.net/manual/en/mongo.connecting.php
//************************
//** Select database and table **//
//***************************
$db=$conn->mydb; #Select mydb database
//$db=$conn->selectDB("mydb"); #Second way of writing
$collection=$db->column; #Select collection (select 'table')
//$collection=$db->selectCollection(‘column’); #Second way of writing
//$collection=$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); #Simple insertion
echo "New record ID:".$array['_id']; #MongoDB will return a record ID
var_dump($result); #Return: bool(true)
//**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. (This parameter is more useful when a large number of records are inserted)
echo "New record ID:".$array['_id']; #MongoDB will return a record ID
var_dump($result); #Return: array(3) { ["err"]=> NULL ["n"]=> int(0) ["ok"]=> float(1) }
Complete writing method
insert($array,array('safe'=>false,'fsync'=>false,'timeout'=>10000))
/*
* *
* Full format: insert ( array $a [, array $options = array() ] )
* insert(array(),array('safe'=>false,'fsync'=>false,'timeout'=>10000))
* Parameter: safe: default false, whether it is safe to write
* fsync: Default is false, whether to force the insertion to be synchronized to the disk
* timeout: timeout time (milliseconds)
*
* Insert result: { “_id” : ObjectId(“4d63552ad549a02c01000009″), “column_name” : “col770″, “column_exp” : “xiaocai” }
* '_id' is the primary key field, which is automatically added by MongoDB during insertion.
*
* Note: 1. 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
* $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”;
* }
*
* Detailed information: http://www.php.net/manual/zh/mongocollection.insert.php
* *
*/
//***************************
//** Update document **//
//***************************
//** Modify and update **/
$where=array(‘column_name’=>’col123′);
$newdata=array(‘column_exp’=>’GGGGGGGG’,’column_fid’=>444);
$result=$collection->update($where,array('$set'=>$newdata)); #$set: Make a node equal to a given value, similar to $pull $pullAll $pop $ inc, I’ll explain how to use it later
/*
* Result:
* Original data
* {“_id”:ObjectId(“4d635ba2d549a02801000003″),”column_name”:”col123″,”column_exp”:”xiaocai”}
* was replaced with
* {“_id”:ObjectId(“4d635ba2d549a02801000003″),”column_name”:”col123″,”column_exp”:”GGGGGGG”,”column_fid”:444}
*/
//**Replacement update **/
$where=array(‘column_name’=>’col709′);
$newdata=array(‘column_exp’=>’HHHHHHHHHH’,’column_fid’=>123);
$result=$collection->update($where,$newdata);
/*
* Result:
* Original data
* {“_id”:ObjectId(“4d635ba2d549a02801000003″),”column_name”:”col709″,”column_exp”:”xiaocai”}
* was 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 91u decreases by 5
*/
/**Delete node **/
$where=array(‘column_name’=>’col685′);
$result=$collection->update($where,array(‘$unset’=>’column_exp’));
/**
* Delete node column_exp
*/
/*
* *
* Full format: update(array $criteria, array $newobj [, array $options = array() ] )
* Note: 1. Pay attention to distinguish between replacement update and modification update
* 2. Pay attention to distinguishing data types such as array(’91u’=>’684435′) and array(’91u’=>684435)
* Detailed information: http://www.mongodb.org/display/DOCS/Updating#Updating-%24bit
* *
*/
//***************************
//** Delete document **//
//***************************
/** Clear database **/
$collection->remove(array(‘column_name’=>’col399′));
//$collection->remove(); #Clear the collection
/**Delete the specified MongoId **/
$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().”
”; #All
echo ‘count:’.$collection->count(array(‘type’=>’user’)).”
”; #You can add conditions
echo 'count:'.$collection->count(array('age'=>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).”
”; #Get the actual number of results returned
/**
* 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 perform the find() operation and obtain the $cursor cursor, the cursor is still dynamic.
* In other words, after I find(), until my cursor loop completes, if any more records that meet the conditions 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();
* For details, 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));
/**
* I will make an error when 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)); ##1 means descending order -1 means ascending order, the order of parameters Affects sort order
/**Index **/
$collection->ensureIndex(array(‘age’ => 1,’type’=>-1)); #1 means descending order -1 means ascending order
$collection->ensureIndex(array('age' => 1,'type'=>-1),array('background'=>true)); #Index creation is run in the background (default is (synchronous operation)
$collection->ensureIndex(array(‘age’ => 1,’type’=>-1),array(‘unique’=>true)); #This index is unique
/**
* ensureIndex (array(),array('name'=>'index name','background'=true,'unique'=true))
* For details, see: http://www.php.net/manual/en/mongocollection.ensureindex.php
*/
/**Get query results **/
$cursor = $collection->find();
$array=array();
foreach ($cursor as $id => $value) {
$array[]=$value;
}
//***************************
//** Document clustering **//
//************************
//I don’t understand this thing...
$conn->close(); #Close the connection
/*
The difference between relational database and MongoDB data storage
MySql data structure:
CREATE TABLE IF NOT EXISTS(
column_idint(16) NOT NULL auto_increment COMMENT ‘primary key’,
column_namevarchar(32) NOT NULL COMMENT ‘column name’,
column_id
PRIMARY KEY ()
article
);
CREATE TABLE IF NOT EXISTS(
article_idint(16) NOT NULL auto_increment COMMENT ‘primary key’,
article_captionvarchar(15) NOT NULL COMMENT ‘title’,
article_id
PRIMARY KEY()
article_body
);
CREATE TABLE IF NOT EXISTS(
article_idint(16) NOT NULL COMMENT ‘article.article_id’,
bodytext COMMENT ‘text’
);
MongoDB data structure:
$data=array(
‘column_name’ =>’default’,
‘article’ =>array(
‘article_caption’ => ‘xiaocai’,
‘body’ => ‘xxxxxxxxxx…’
)
);
$inc
If the recorded node exists, add N to the node value; if the node does not exist, let the node value equal N
Suppose the structure record structure is array(’a’=>1,’b’=>’t’), and you want to add 5 to a, then:
$coll->update(
array('b'=>'t'),
array(’$inc’=>array(’a’=>5)),
)
$set
Let a node equal the given value
Suppose the structure record structure is array(’a’=>1,’b’=>’t’), b is plus f, then:
$coll->update(
array('a'=>1),
array(’$set’=>array(’b’=>’f’)),
)
$unset
Delete a node
Assume the record structure is array(’a’=>1,’b’=>’t’), and you want to delete the b node, then:
$coll->update(
array('a'=>1),
array(’$unset’=>’b’),
)
$push
If the corresponding node is an array, append 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.
Suppose the record structure is array('a'=>array(0=>'haha'),'b'=>1), and you want to append new data to node a, then:
$coll->update(
array('b'=>1),
array(’$push’=>array(’a’=>’wow’)),
)
In this way, the record will become: array('a'=>array(0=>'haha',1=>'wow'),'b'=>1)
$pushAll
Similar to $push, except that multiple values will be appended to a node at one time
$addToSet
If a value is not in the array at this stage, add it
Suppose the record structure is array('a'=>array(0=>'haha'),'b'=>1). If you want to append new data to the node a, then:
$coll->update(
array('b'=>1),
array(’$addToSet’=>array(’a’=>’wow’)),
)
If there is already wow in node a, then no new one will be added. If not, a new item - wow will be added to the node.
$pop
Let the record be array('a'=>array(0=>'haha',1=>'wow'),'b'=>1)
Delete the last element of an array node:
$coll->update(
array('b'=>1),
array(’$pop=>array(’a’=>1)),
)
Delete the first element of an array stage
$coll->update(
array('b'=>1),
array(’$pop=>array(’a’=>-1)),
)
$pull
If the node is an array, delete the child whose value is value. If it is not an array, an error will be returned.
Suppose the record is array('a'=>array(0=>'haha',1=>'wow'),'b'=>1), and you want to delete the child with value haha in a Item:
$coll->update(
array('b'=>1),
array(’$pull=>array(’a’=>’haha’)),
)
The result is: array('a'=>array(0=>'wow'),'b'=>1)
$pullAll
Similar to $pull, except that it can delete a group of records that meet the conditions.
*/
?>
The above introduces the PHP operation MongoDB study notes, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.