Giter VIP home page Giter VIP logo

mongodb-php-examples's Introduction

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' => '[email protected]',
    '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' => '[email protected]',
        'createdAt' => new \DateTime(),
    ],
    [
        'firstName' => 'Adam',
        'lastName' => 'West',
        'email' => '[email protected]',
        'createdAt' => new \DateTime(),
    ]
];
$dm->selectCollection('Users')->insertMany($users);

Update one document

$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 .


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'] = '[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.


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.

mongodb-php-examples's People

Contributors

vsg24 avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

krishan-nattar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.