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.
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.
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.
$user = (array) $dm->selectCollection('Users')->findOne(['_id' => new ObjectID($id)]);
$users = $dm->selectCollection('Users')->find([])->toArray();
$user = [
'firstName' => 'John',
'lastName' => 'Doe',
'email' => '[email protected]',
'createdAt' => new \DateTime(),
];
$dm->selectCollection('Users')->insertOne($user);
An _id
field is automatically generated and added to the document by MongoDB.
$users = [
[
'firstName' => 'John',
'lastName' => 'Doe',
'email' => '[email protected]',
'createdAt' => new \DateTime(),
],
[
'firstName' => 'Adam',
'lastName' => 'West',
'email' => '[email protected]',
'createdAt' => new \DateTime(),
]
];
$dm->selectCollection('Users')->insertMany($users);
$dm->selectCollection('Users')->updateOne(
['email' => '[email protected]'],
['$set' => ['username' => 'ad_west']]
);
The above code finds a user with the email [email protected]
and sets its username
field to ad_west
. The username
field will be created and initialized, If the user doesn't have one .
$dm->selectCollection('Users')->updateMany(
[],
['$set' => ['updatedAt' => new \DateTime()]]
);
Update all documents in the Users
collection and set their updatedAt
field to the current DateTime
.
$dm->selectCollection('Users')->deleteOne(['firstName' => 'John']);
$dm->selectCollection('Users')->deleteMany([]);
The above code deletes all documents in the Users
collection.
$dm->createCollection('Articles');
$dm->dropCollection('Articles');
The above code completely removes the Articles
collection. All documents inside it will be lost.
// 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'] = '[email protected]';
$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 [email protected]
.
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.
$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.
$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
.