1. Connect to MongoDB
<? php // 1. Connect to MongoDB $host = "127.0.0.1" ; $port = 27017 ; $server = "mongodb:// $host : $port " ; $mongodb = new MongoClient( $server ); echo "<pre>" ; var_dump ( $mongodb ); // 2. Select database $db = $client -> hytc; var_dump ( $db ); // 3. Select data table $collection =$db -> user; var_dump($collection);
Note: libraries and tables do not need to be created manually, they are created automatically after selection
2. CRUD operations
insert (data) insert data (must be an array)
//插入文档(关联数组) $data = ["name"=>"小明","age"=>10,"hobby"=>"swim"]; $result = $collection -> insert($data);
echo "<pre>";var_dump($result);
find (find conditions, find fields) query data
// Query 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 => document content) update data
// Update data $condition = ['name'=>'Xiao Ming' ]; $new_doc = [ '$set' => ["hobby" => "swim" ] ]; $result = $collection -> update($condition,$new_doc); echo "<pre>"; var_dump($result);
Note:
- If the hobby field does not exist, create the field
- The default update does a replacement operation, which can be modified instead of replaced by the attribute modifier
- If multiple records meet the update conditions, only the first data will be updated by default
- To update all records that meet the update conditions, set the third parameter of this function: ["multiple"=>true]
//更新数据 $condition = ['age'=>'20']; $new_doc = [ '$set' => ["hobby" => "swim"] ]; $result = $collection -> update($condition,$new_doc,['multiple'=>true]); echo "<pre>"; var_dump($result);
remove (find condition) delete data
// Delete data $condition = ['name'=>'Xiao Ming' ]; $result = $collection -> remove( $condition );