Examples of using MongoDB with PHP
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.DS_Store
LICENSE
README.MD

README.MD

MongoDB PHP Examples

The following cheatsheet assumes that you are using MongoDB 3.4 with PHP 7.1+. In order to connect your PHP app to MongoDB you should install the official MongoDB driver for PHP and use mongo-php-library to execute queries.


Setup

We'll have a database named Blog with the following collections:

  • Users
  • Articles

Each document in our collections will have the an _id field generated by MongoDB. We can use it to find documents as needed. In order to make it easy to access query results we'll convert the result of each query to an associative array.

The MongoDB instance

In order to connect to database and execute queries we need to create a MongoDB object.

In this tutorial we'll call it $dm (Document Manager). Here's how we'll set it up:

$username_password = MONGO_DB_USERNAME != null && MONGO_DB_USERNAME != "" ? MONGO_DB_USERNAME . ':' . MONGO_DB_PASSWORD . '@' : "";
$host_and_port = MONGO_DB_HOST . ':' . MONGO_DB_PORT;
$mongoClient = new Client('mongodb://' . $username_password . $host_and_port, [], [
    'typeMap' => [
        'array' => 'array',
        'document' => 'array',
        'root' => 'array',
    ],
]);

$dm = $mongoClient->selectDatabase(MONGO_DB_DEFAULT_DATABASE_NAME ?? 'Blog');

We used several constants for storing connection info that you should define before the above code according to your environment.


1- Basic examples

Find a single document

$user = (array) $dm->selectCollection('Users')->findOne(['_id' => new ObjectID($id)]);

Find many documents

$users = $dm->selectCollection('Users')->find([])->toArray();

Insert one document

$user = [
    'firstName' => 'John',
    'lastName' => 'Doe',
    'email' => 'john.doe@example.com',
    'createdAt' => new \DateTime(),
];
$dm->selectCollection('Users')->insertOne($user);

An _id field is automatically generated and added to the document by MongoDB.


Insert many documents

$users = [
    [
        'firstName' => 'John',
        'lastName' => 'Doe',
        'email' => 'john.doe@example.com',
        'createdAt' => new \DateTime(),
    ],
    [
        'firstName' => 'Adam',
        'lastName' => 'West',
        'email' => 'adam.west@example.com',
        'createdAt' => new \DateTime(),
    ]
];
$dm->selectCollection('Users')->insertMany($users);

Update one document

$dm->selectCollection('Users')->updateOne(
    ['email' => 'adam.west@example.com'],
    ['$set' => ['username' => 'ad_west']]
);

The above code finds a user with the email adam.west@example.com and sets its username field to ad_west . The username field will be created and initialized, If the user doesn't have one .


Update many documents

$dm->selectCollection('Users')->updateMany(
    [],
    ['$set' => ['updatedAt' => new \DateTime()]]
);

Update all documents in the Users collection and set their updatedAt field to the current DateTime.


Delete one document

$dm->selectCollection('Users')->deleteOne(['firstName' => 'John']);

Delete many documents

$dm->selectCollection('Users')->deleteMany([]);

The above code deletes all documents in the Users collection.


2- Advanced examples

Create a collection

$dm->createCollection('Articles');

Drop (Remove) a collection

$dm->dropCollection('Articles');

The above code completely removes the Articles collection. All documents inside it will be lost.


Advanced Search

Multiple conditions

// Input
$tags = ['cat', 'dog'];
$search = 'puppy';

// Building the search query
$query = [];
$query['$or'] = [
    ['title' => new \MongoDB\BSON\Regex("$search", '')],
    ['category' => new \MongoDB\BSON\Regex("$search", '')],
];

$query['tags'] = [
    '$in' => $tags
];

// nested array element check
$query['author.email'] = 'adam.west@example.com';

$list = $dm->selectCollection('Articles')->find($query)->toArray();

The above code will find any article that includes the keyword puppy in its title OR category AND has a cat OR dog tag in its array of tags Also the author of the article must have an email equal to adam.west@example.com.

The $in operator should be used when performing equality checks on the same field. The $or operator could be used to match conditions between multiple fields.


Working with arrays

Pushing to an array (Adding to array)

$dm->selectCollection('Articles')->updateOne(
    ['title' => 'Hello world!'],
    ['$push' => ['tags' => 'hello']]
);

The above snippet updates the first article with the title Hello World! and appneds hello to its tags array.

You can also append multiple values to an array using the $pushAll operator.

Pulling from an array (Removing from array)

$this->dm->selectCollection('Articles')->updateMany(
    [
        'status' => ['$ne' => 'published']
    ],
    [
        '$pull' => ['tags' => ['enabled' => false]],
    ],
    [
        'multiple' => true
    ]
);

The above code removes all tags that have a enabled field with the boolean value false. It only works on documents that have a status field that is NOT equal to published.