Summary of common MongoDB operations in PHP
- 2021-01-14 05:42:28
- OfStack
$mongodb = new Mongo();
//$connection = new Mongo( "$dburl:$port" ); // connect to a remote host (default port)
$mydb = $mongodb- > mydb; // Create database mydb
$mydb = $mongodb- > selectDB("mydb"); // Select the existing database directly
$collection = $mydb- > mycollect; // Select the corpus used. If it does not exist, create it automatically
$collection = $db- > selectCollection('mydb'); // Select only, not create
// Insert new record
$collection- > insert(array("name"= > "l4yn3", "age"= > "10", "sex":"unknow"));
// Modify the record
$where = array("name"= > "l4yn3");
$update_item = array('$set'= > array("age"= > "15", "sex":"secret"));
$collection- > update($where, $update_item);
$options['multiple'] = true; // The default is false, whether to change the matching multiple lines
$collection- > update($where, $update_item, $options);
// query records
$myinfo = $collection- > findOne(array("name"= > "l4yn3"));
$myinfo = $collection-
>
findOne(array("name"=
>
"l4yn3"), array("age"=
>
"15"));
// Search by condition:
$query = array("name"=
>
"l4yn3");
$cursor = $collection-
>
find($query); $collectio = $query; $collectio = $query
while($cursor-
>
hasNext())
{
var_dump($cursor-
>
getNext()); // Returns an array
}
// Returns the number of documentation records
$collection- > count();
// delete 1 database:
$connection-
>
dropDB("...");
// list all available databases:
$m-
>
listDBs(); // No return value
// Close the connection:
$connection-
>
close();
php Various parametric ways to connect to mongodb databases
/ / connect localhost: 27017
$conn = new Mongo();
// Connect to the default port of the remote host
$conn = new Mongo('test.com');
// Connect to the remote host port 22011
$conn = new Mongo('test.com:22011');
//MongoDB UseName Password
$conn = new Mongo("mongodb://${username}:${password}@localhost")
//MongoDB is a user name with a password and the database blog is specified
$conn = new Mongo("mongodb://${username}:${password}@localhost/blog");
// Multiple servers
$conn = new Mongo("mongodb://localhost:27017,localhost:27018");