php mongodb extension

allway2發表於2020-10-06

To install the mongodb extension, do:

sudo apt-get install php-mongodb
dnf install php-mongodb

<?php

    use MongoDB\Driver\Manager;

    try {
        $manager = new Manager("mongodb://localhost:27017/mymongodatabase");
    } catch (MongoDB\Driver\Exception\Exception $e) {
        echo "Exception:", $e->getMessage(), "\n";
        echo "On line:", $e->getLine(), "\n";     
    }
    
    
    $query = new MongoDB\Driver\Query([]);
    $rows = $manager->executeQuery("mymongodatabase.users", $query);
    foreach ($rows as $row) {
        echo $row->id;
        echo $row->firstname;
        echo $row->lastname;
        echo $row->address->street;
        echo $row->address->city;
        echo $row->address->country;
    }
    
    $id = 1;
    $firstname = "John";
    $lastname = "Doe";
    $street = "Best Avenue";
    $city = "Los Angeles";
    $country = "USA";
            
    try {
        $bulk = new MongoDB\Driver\BulkWrite();
        $doc = ['id' => $id, 'firstname' => $firstname, 'lastname' => $lastname,
                'address' => ['street' => $street, 'city' => $city,
                'country' => $country]];
        $bulk->insert($doc);
        $result = $manager->executeBulkWrite('mymongodatabase.users', $bulk); 
    } catch (MongoDB\Driver\Exception\Exception $e) {
        echo "Exception:", $e->getMessage(), "\n";
        echo "On line:", $e->getLine(), "\n";
    }
    
?>

Connect to MongoDB
Create a MongoDB connection, that later you can query:

$manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
In the next example, you will learn how to query the connection object.

This extension close the connection automatically, it's not necessary to close manually.

Delete a document
Example for deleting all documents where name is equal to "Peter":

$bulk = new \MongoDB\Driver\BulkWrite;

$filter = ['name' => 'Peter'];
$bulk->delete($filter);

$result = $manager->executeBulkWrite('database_name.collection_name', $bulk);
Get multiple documents - find()
Example for searching multiple users with the name "Mike":

$filter = ['name' => 'Mike'];
$query = new \MongoDB\Driver\Query($filter);

$cursor = $manager->executeQuery('database_name.collection_name', $query);
foreach ($cursor as $doc) {
    var_dump($doc);
}
Get one document - findOne()
Example for searching just one user with a specific id, you should do:

$options = ['limit' => 1];
$filter = ['_id' => new \MongoDB\BSON\ObjectID('578ff7c3648c940e008b457a')];
$query = new \MongoDB\Driver\Query($filter, $options);

$cursor = $manager->executeQuery('database_name.collection_name', $query);
$cursorArray = $cursor->toArray();
if(isset($cursorArray[0])) {
    var_dump($cursorArray[0]);
}
Insert document
Example for adding a document:

$document = [
    'name' => 'John',
    'active' => true,
    'info' => ['genre' => 'male', 'age' => 30]
];
$bulk = new \MongoDB\Driver\BulkWrite;
$_id1 = $bulk->insert($document);
$result = $manager->executeBulkWrite('database_name.collection_name', $bulk);
Update a document
Example for updating all documents where name is equal to "John":

$filter = ['name' => 'John'];
$document = ['name' => 'Mike'];

$bulk = new \MongoDB\Driver\BulkWrite;
$bulk->update(
    $filter,
    $document,
    ['multi' => true]
);
$result = $manager->executeBulkWrite('database_name.collection_name', $bulk);


<?php

// Connect to phpTester database
$manager = new MongoDB\Driver\Manager("mongodb://php-tester:123@localhost:27017/phpTester");

// Insert a document
$bulkWrite=new MongoDB\Driver\BulkWrite;
$doc=array("title" => "PHP Tester", "description" => "Test PHP code online");
$bulkWrite->insert($doc);
$manager->executeBulkWrite('phpTester.example', $bulkWrite);

// Get all documents
$query = new MongoDB\Driver\Query(array());
$cursor = $manager->executeQuery('phpTester.example', $query);

// Convert to Array and print result
print_r($cursor->toArray());

// Delete all documents
$bulkDelete = new MongoDB\Driver\BulkWrite;
$bulkDelete->delete(['title' => 'PHP Tester' ], ['limit' => 0]);

$manager->executeBulkWrite('phpTester.example', $bulkDelete);


?>

相關文章