Coder Social home page Coder Social logo

php-mongodb's Introduction

php-mongodb

php-mongodb is a PHP library that wraps MongoDB\Client library and provides a clean api for interacting with MongoDB database.

# System requirements

  • >=php7.2
  • php7.x-mongodb extension
  • mongodb php driver

# Installation

  • Install mongodb driver
    • apt update && apt upgrade -y
    • pecl install mongodb-1.9.0
  • Install this library via composer
    • composer install crazymeeks/php-mongodb

# Usage

Connect to MongoDB Database

use Crazymeeks\MongoDB\Facades\Connection;

Connection::setUpConnection('127.0.0.1', ['username' => 'root', 'password' => 'root'], [])
          ->setDefaultDatabase('testing_mytestdb_crzymix')
          ->connect();

Extend Crazymeeks\MongoDB\Model\AbstractModel class

namespace Some\Namespace;

use Crazymeeks\MongoDB\Model\AbstractModel;

class User extends AbstractModel
{

    // Required
    protected $collection = 'users';

    // Required
    protected $fillable = [
        'firstname',
        'lastname',
        'email',
    ];
}

# Inserting data

First approach:

$user = new User([
    'firstname' => 'John',
    'lastname' => 'Doe',
    'email' => '[email protected]',
]);
$user->save();
echo $user->firstname;
// result: John

Second approach:

$user = User::create([
    'firstname' => 'John',
    'lastname' => 'Doe',
    'email' => '[email protected]',
]);

echo $user->firstname;
// result: John

Note: save() and create() methods will automatically add created_at and updated_at
timestamps fields when performing an insert. If you wish to disable this, just add protected $timestamps = true; to your model class.
Or error, this will throw \Exception or \Error when something went wrong.

# Update

Single

$user = new User();
$user->whereEq('firstname', 'John')
     ->update([
         'firstname' => 'Jane',
     ]);

Bulk update

$user = new User();
$user->whereEq('firstname', 'John')
     ->updateMany([
         'firstname' => 'Jane',
     ]);

# Delete

Single

$user = new User();
$user->whereEq('firstname', 'John')
     ->delete();

Bulk delete

$user = new User();
$user->whereEq('firstname', 'John')
     ->deleteMany();

# Finding or Querying data from collection.

Current methods available

whereEq(string $field, string $value) - where equal query and case-insentive.
whereNotEq(string $field, string $value) - where not equal query and case-insensitive.
whereIn(string $field, array($value1, $value2, ...)) - Case-insensitive.
whereNotIn(string $field, array($value1, array $value2, ...)) - Case-insensitive.
whereGreater(string $field, mixed $value) $value could be int|string. Works great for int types.
whereGreaterOrEq(string $field, mixed $value) - $value could be int|string. Works great for int types.
whereLessThanOrEq(string $field, mixed $value) - $value could be int|string. Works great for int types.
whereLessThan(string $field, mixed $value) - $value could be int|string. Works great for int types.
first() - Returns object that extends \Crazymeeks\MongoDB\Model\AbstractModel. You may count() result of this function for counter checking.
get() - Returns an array object that extends \Crazymeeks\MongoDB\Model\AbstractModel. You may count() result of this function for counter checking.

# Query samples

$user = new User();
$result = $user->whereEq('firstname', 'John')->first();
if (count($result) > 0) {
    echo $result->firstname;
    // result: John
}

# Chaining multiple queries

You may chain multiple queries too.

$user = new User();
$users = $user->whereEq('email', '[email protected]')
                ->whereIn('name', ['john'])
                ->get();
foreach($users as $user){
    echo $user->name . "<br>";
}
// or you may also call methods statically
$users = User::whereEq('email', '[email protected]')
                ->whereIn('name', ['john'])
                ->get();

# Laravel integration

Register connection to app service provider.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Crazymeeks\MongoDB\Facades\Connection;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        
        Connection::setUpConnection('127.0.0.1', ['username' => 'root', 'password' => 'root'], [])
          ->setDefaultDatabase('testing_mytestdb_crzymix')
          ->connect();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

Model

namespace App;

use Crazymeeks\MongoDB\Model\AbstractModel;

class User extends AbstractModel
{
    protected $collection = 'users';

    protected $fillable = [
        'firstname',
        'lastname',
        'email',
    ];

}

Important: Laravel's relationship is not yet supported.

php-mongodb's People

Watchers

James Cloos avatar

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.