Home  >  Article  >  Backend Development  >  How to implement non-relational database operations using PHP and MongoDB

How to implement non-relational database operations using PHP and MongoDB

王林
王林Original
2023-06-25 10:34:381272browse

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:

  1. Download PHP extension: Download the source code of the corresponding version of the MongoDB extension (https://pecl.php.net/package/mongodb) from the PECL official website, and Unzip.
  2. Compile PHP extension: Enter the source code folder on the command line and execute the following command:

    phpize
    ./configure
    make
    make install
  3. Configure the php.ini file: Find php.ini file and add the following content:

    extension=mongodb.so
  4. 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:

  1. 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");
  2. 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:

  1. Create document: Use MongoDB's document class MongoDBBSONDocument to create a document object.

    $doc = new MongoDBBSONDocument([
        'name' => '张三',
        'age' => 20,
        'sex' => '男',
        'address' => '北京市',
    ]);
  2. 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:

  1. 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'] . "
    ";
    }
  2. 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:

  1. 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]]
    );
  2. Multiple updates: Use the updateMany method to update data in batches.

    $collection = $db->selectCollection('users');
    $collection->updateMany(
        ['sex' => '男'],
        ['$inc' => ['age' => 1]]
    );
  3. 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' => '张三']);
  4. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn