Detailed examples of PHP operations on MongoDB (add, delete, modify, and query) (6) PHP operations on mongodb:
Modules are required for PHP to operate mongodb.
Official website can download: http://pecl.php.net/package/mongo download
Set mongodb to user-authorized startup mode
The php Manual does not have some user authorization methods for login:
Conn. php
$ Conn = new Mongo ("mongodb: // user1: 123456 @ localhost: 27017/test"); // link to the mongodb test database authorized by the user
$ Db = $ conn-> test;
?>
Find. php
Include "conn. php ";
$ C1 = $ db-> c1; // operates the c1 set.
// Json cannot be used directly in php
// Db. c1.find ({name: "user1 "});
// {Name: "user1" }== array ("name" => "user1") in this form
// [1, 2] = array (1, 2 );
// {} = Array ()
$ Arr = array ();
$ Rst = $ c1-> find ($ arr );
Foreach ($ rst as $ val ){
Echo"
";
Print_r ($ val ['name']); // Obtain "_ id" if the id is used"
}
Example 2: query with specified values
$ Arr = array ("name" => "user1"); // query
$ Rst = $ c1-> find ($ arr );
Foreach ($ rst as $ val ){
Echo"";
$ Fs = $ val ['_ id'];
Print_r ($ val );
Echo ""; // you will find that the fid is converted into a string when it is uploaded to user. php. how can this problem be solved?
// User. php query mongodb data based on _ id
Include "conn. php ";
$ C1 = $ db-> c1;
$ Oid = new Upload ID ($ _ GET ['fid']); use this to go through
Var_dump ($ oid); // or Object. If this parameter is not converted, it is of the string type.
$ Arr = array ("_ id" => "$ oid ");
$ Rst = $ c1-> find ($ arr );
Foreach ($ rst as $ val ){
Echo"";
Print_r ($ val );
}
?>
}
Example 3: Add
Include "conn. php ";
$ C1 = $ db-> c1;
// Db. c1.insert ({"name" => "user3", age: 30, "sex" => "nan "});
$ Arr = array ("name" => "user3", "age" => 30, "sex" => "nan ");
If ($ c1-> insert ($ arr ))
Echo 'successfully ';
Else
Echo 'failed ';
Example 4: delete
Include "conn. php ";
$ C1 = $ db-> c1;
// Db. c1.remove ({"name" => "user2 "});
$ Arr = array ("name" => "user2 ");
If ($ c1-> remove ($ arr ))
Echo 'deleted successfully ';
Else
Echo 'deletion failed ';
Example 4: Modify
Include "conn. php ";
$ C1 = $ db-> c1;
// Db. c1.update ({"name" => "user2"}, {$ set: {age: 20, sex: "nan"}); add a field
$ Sarr = array ("name" => "user2 ");
$ Darr = array ('$ set' => array ('Sex' => 'Nan', 'age' => 24 ));
$ Opts = array ('upsert '=> 0, 'multiple' => 1 );
If ($ c1-> update ($ sarr, $ darr, $ opts) // update in php can only pass three parameters
Echo 'changed successfully ';
Else
Echo 'change failed ';
// Close
$ Conn-> close ();
?>