1. Connect MongoDB
<?PHP//1. Connect to MongoDB $host= "127.0.0.1"; $port= 27017; $server= "mongodb://$host:$port"; $mongodb=NewMongoclient ($server); Echo"<pre>"; Var_dump($mongodb); //2. Select a database $db=$client-HYTC; Var_dump($db); //3. Select a data table $collection=$db-user; Var_dump($collection);
Note: libraries, tables do not need to be created manually, automatically created after selection
2. CRUDOperation
Insert (data) inserts data (must be an array)
// Insert document (associative array) $data = ["Name" = "Xiao Ming", "Age" =>10, "hobby" = "swim"]; Insert ($data), $result$collection
Echo "<pre>";
Var_dump ($result);
Find (Find criteria, lookup fields) query data
//Querying data (returns cursor cursor, resource) $condition= [' Name ' = ' Xiao Ming ']; $fields= [ ' _id ' =false,//do not query ID' Name ' + =true,//Query Name' Hobby ' =true //Query Hobby ]; $result=$collection-Find ($condition,$fields); foreach($result as $key=$value){ Echo"<pre>"; Var_dump($value); }
Update (Find condition, content after update, and content of document) updates data
// Update Data $condition = [' name ' = ' xiaoming ']; $new _doc = [ ' $set ' + = ["hobby" = "swim"] ] ; $result $collection Update ($condition,$new _doc); Echo "<pre>"; Var_dump ($result);
Note:
- If the Hobby field does not exist, the field is created
- The default update is replaced by the property modifier instead of replacing
- If more than one record meets the update criteria, only the first data is updated by default
- If you want to update all records that meet the update criteria,set the third parameter of the function:["Multiple" =>true]
// Update Data $condition = [' age ' = ' + ']; $new _doc = [ ' $set ' + = ["hobby" = "swim"] ] ; $result Update $collection -$condition,$new _doc, [' multiple ' =true ]); Echo "<pre>"; Var_dump ($result);
Remove (find condition) Delete data
// Delete Data $condition = [' name ' = ' xiaoming ']; $result $collection , remove ($condition);
MongoDB related Operations