MongoDB operations have always been performed through the mongo client process. But in reality, our operations on MOngoDB data are often implemented through corresponding programs, such as php, java or Python. So how to operate MongoDB in php?
Configuring MongoDB in PHP
Configuring MongoDB in php.ini is quite simple, just add the following code That’s it
extension=php_mongo.dll
The main thing to note is that the php_mongo.dll version must correspond to the current php version. Otherwise, an incompatibility error will occur. (Recommended learning: PHP video tutorial)
Regarding the download of php_mongo.dll, you can download it from http://pecl.php.net/package/mongo. There are many versions available to choose from.
Connecting to MongoDB in PHP
First you must open the MongoDB service
We all know that to connect to the Mysql database in PHP, we can use Mysqli or Pdo class, so is there a corresponding class for connecting to MongoDB? The answer is yes. This class is MongoClient. It is the connection manager for PHP and MongoDB, responsible for creating and managing connections. The structure of the class is as follows:
MongoClient { /* 常量 */ const string VERSION ; const string DEFAULT_HOST = "localhost" ; const int DEFAULT_PORT = 27017 ; const string RP_PRIMARY = "primary" ; const string RP_PRIMARY_PREFERRED = "primaryPreferred" ; const string RP_SECONDARY = "secondary" ; const string RP_SECONDARY_PREFERRED = "secondaryPreferred" ; const string RP_NEAREST = "nearest" ; /* 属性 */ public boolean $connected = FALSE ; public string $status = NULL ; protected string $server = NULL ; protected boolean $persistent = NULL ; /* 方法 */ public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] ) public bool close ([ boolean|string $connection ] ) public bool connect ( void ) public array dropDB ( mixed $db ) public MongoDB __get ( string $dbname ) public static array getConnections ( void ) public array getHosts ( void ) public array getReadPreference ( void ) public array getWriteConcern ( void ) public bool killCursor ( string $server_hash , int|MongoInt64 $id ) public array listDBs ( void ) public MongoCollection selectCollection ( string $db , string $collection ) public MongoDB selectDB ( string $name ) public bool setReadPreference ( string $read_preference [, array $tags ] ) public bool setWriteConcern ( mixed $w [, int $wtimeout ] ) public string __toString ( void ) }
Querying MongoDB data in PHP
In the MongoDB extension module of PHP, MongoCollection is provided to perform CURD operations on data.
The above is the detailed content of How to use momgodb transaction in php. For more information, please follow other related articles on the PHP Chinese website!