Home > Article > Backend Development > How to implement non-relational database operations using PHP and MongoDB
With the development of the Internet, the amount of data has increased dramatically, and traditional relational databases can no longer fully meet the needs of data processing. As a new database technology, non-relational database (NoSQL) can better handle massive data and high concurrent access situations. Among them, MongoDB, as one of the representatives of Nosql, supports dynamic data schema, high scalability, high availability and high performance, and is especially suitable for object-oriented development models. This article will introduce how to use PHP and MongoDB to implement non-relational database operations.
1. Install MongoDB and PHP extensions
Before using MongoDB, you first need to install the MongoDB service and the corresponding PHP extension. For the installation of MongoDB, please refer to the official documentation and will not go into details here. The installation of PHP extension can be carried out through the following steps:
Compile PHP extension: Enter the source code folder on the command line and execute the following command:
phpize ./configure make make install
Configure the php.ini file: Find php.ini file and add the following content:
extension=mongodb.so
Restart the PHP service: Restart the PHP service to make the configuration take effect. The command method varies according to different systems, such as:
systemctl restart php-fpm
2. Connect to MongoDB database
Connecting to MongoDB database requires the use of the PHP driver provided by MongoDB. The specific operations are as follows:
Create a connection: Use the MongoClient class to create a connection , the parameters of its constructor are the IP address and port number of the MongoDB service.
$client = new MongoClient("mongodb://127.0.0.1:27017");
Select database: Use the selectDB method to select the database to operate.
$db = $client->selectDB('test');
3. Insert data
MongoDB supports data storage in JSON format, so inserting data can convert the data into JSON format. The specific operations are as follows:
Create document: Use MongoDB's document class MongoDBBSONDocument to create a document object.
$doc = new MongoDBBSONDocument([ 'name' => '张三', 'age' => 20, 'sex' => '男', 'address' => '北京市', ]);
Insert data: Use the insertOne method of MongoDB's collection class MongoCollection to insert data.
$collection = $db->selectCollection('users'); $collection->insertOne($doc);
4. Query data
MongoDB supports a variety of powerful query and aggregation operations. The specific operations are as follows:
Query documents: Use the find method to query documents, where the first parameter is the query condition, and the second parameter is optional, such as querying specified fields, sorting, etc.
$collection = $db->selectCollection('users'); $cursor = $collection->find([ 'age' => ['$gt' => 18] ], [ 'projection' => ['name' => 1, 'age' => 1], 'sort' => ['age' => 1], ]); foreach ($cursor as $doc) { echo $doc['name'] . ' ' . $doc['age'] . " "; }
Aggregation operation: Use aggregation methods, such as aggregate method, to perform multi-level aggregation calculations to achieve complex query requirements.
$collection = $db->selectCollection('users'); $cursor = $collection->aggregate([ ['$match' => ['age' => ['$gt' => 18]]], ['$group' => [ '_id' => '$sex', 'count' => ['$sum' => 1] ]], ['$sort' => ['count' => -1]], ]); foreach ($cursor as $doc) { echo $doc['_id'] . ' ' . $doc['count'] . " "; }
5. Update and delete data
MongoDB supports single and batch update and delete operations. The specific operations are as follows:
Single update: Use the updateOne method to update a single piece of data, where the first parameter is the query condition and the second parameter is the data to be updated.
$collection = $db->selectCollection('users'); $collection->updateOne( ['name' => '张三'], ['$set' => ['age' => 21]] );
Multiple updates: Use the updateMany method to update data in batches.
$collection = $db->selectCollection('users'); $collection->updateMany( ['sex' => '男'], ['$inc' => ['age' => 1]] );
Single deletion: Use the deleteOne method to delete a single piece of data, where the first parameter is the query condition.
$collection = $db->selectCollection('users'); $collection->deleteOne(['name' => '张三']);
Multiple deletions: Use the deleteMany method to delete data in batches.
$collection = $db->selectCollection('users'); $collection->deleteMany(['sex' => '男']);
6. Summary
The above is a basic introduction to using PHP and MongoDB to implement non-relational database operations. The specific implementation methods of different business scenarios may be different. Readers It can be adjusted and expanded according to the actual situation. MongoDB provides a rich set of operating APIs and aggregation methods to better meet complex business needs.
The above is the detailed content of How to implement non-relational database operations using PHP and MongoDB. For more information, please follow other related articles on the PHP Chinese website!