PHP code example of convenia / laravel-mongodb

1. Go to this page and download the library: Download convenia/laravel-mongodb library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

convenia / laravel-mongodb example snippets


Convenia\Mongodb\MongodbServiceProvider::class,

$app->register(Convenia\Mongodb\MongodbServiceProvider::class);

$app->withEloquent();

$capsule->getDatabaseManager()->extend('mongodb', function($config, $name) {
    $config['name'] = $name;

    return new Convenia\Mongodb\Connection($config);
});

use Illuminate\Foundation\Testing\DatabaseMigrations;

use DatabaseMigrations;

'mongodb' => [
    'driver' => 'mongodb',
    'dsn' => env('DB_DSN'),
    'database' => env('DB_DATABASE', 'homestead'),
],

'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE', 'homestead'),
    'username' => env('DB_USERNAME', 'homestead'),
    'password' => env('DB_PASSWORD', 'secret'),
    'options' => [
        'appname' => 'homestead',
    ],
],

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    //
}

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $collection = 'my_books_collection';
}

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $primaryKey = 'id';
}

// MongoDB will also create _id, but the 'id' property will be used for primary key actions like find().
Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']);

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $connection = 'mongodb';
}

use Convenia\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable
{

}

use Convenia\Mongodb\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    protected $casts = ['birthday' => 'datetime'];
}

$users = User::where(
    'birthday', '>',
    new DateTime('-18 years')
)->get();

$users = User::all();

$user = User::find('517c43667db388101e00000f');

$posts =
    Post::where('author.name', 'John')
        ->take(10)
        ->get();

$posts =
    Post::where('votes', '>', 0)
        ->orWhere('is_approved', true)
        ->get();

$users =
    User::where('age', '>', 18)
        ->where('name', '!=', 'John')
        ->get();

$users = User::whereIn('age', [16, 18, 20])->get();

$posts = Post::whereBetween('votes', [1, 100])->get();

$users = User::whereNull('age')->get();

$users = User::whereDate('birthday', '2021-5-12')->get();

$users =
    User::where('name', 'John')
        ->orWhere(function ($query) {
            return $query
                ->where('votes', '>', 100)
                ->where('title', '<>', 'Admin');
        })->get();

$users = User::orderBy('age', 'desc')->get();

$users =
    User::skip(10)
        ->take(5)
        ->get();

$users =
    Users::groupBy('title')
        ->get(['title', 'name']);

$users = User::distinct()->get(['name']);

// Equivalent to:
$users = User::distinct('name')->get();

$users =
    User::where('active', true)
        ->distinct('name')
        ->get();

$spamComments = Comment::where('body', 'like', '%spam%')->get();

$total = Product::count();
$price = Product::max('price');
$price = Product::min('price');
$price = Product::avg('price');
$total = Product::sum('price');

$sold = Orders::where('sold', true)->sum('price');

$total = Order::max('suborder.price');

Cat::where('name', 'Kitty')->increment('age');

Car::where('name', 'Toyota')->decrement('weight', 50);

$count = User::increment('age');

Cat::where('age', 3)
    ->increment('age', 1, ['group' => 'Kitty Club']);

Car::where('weight', 300)
    ->decrement('weight', 100, ['latest_change' => 'carbon fiber']);

User::where('age', 'exists', true)->get();

User::where('roles', 'all', ['moderator', 'author'])->get();

Post::where('tags', 'size', 3)->get();

use MongoDB\BSON\Regex;

User::where('name', 'regex', new Regex('.*doe', 'i'))->get();

User::where('name', 'regexp', '/.*doe/i')->get();

User::where('name', 'not regexp', '/.*doe/i')->get();

User::where('age', 'type', 2)->get();

User::where('age', 'mod', [10, 0])->get();

$bars = Bar::where('location', 'near', [
    '$geometry' => [
        'type' => 'Point',
        'coordinates' => [
            -0.1367563, // longitude
            51.5100913, // latitude
        ],
    ],
    '$maxDistance' => 50,
])->get();

$bars = Bar::where('location', 'geoWithin', [
    '$geometry' => [
        'type' => 'Polygon',
        'coordinates' => [
            [
                [-0.1450383, 51.5069158],
                [-0.1367563, 51.5100913],
                [-0.1270247, 51.5013233],
                [-0.1450383, 51.5069158],
            ],
        ],
    ],
])->get();

$bars = Bar::where('location', 'geoIntersects', [
    '$geometry' => [
        'type' => 'LineString',
        'coordinates' => [
            [-0.144044, 51.515215],
            [-0.129545, 51.507864],
        ],
    ],
])->get();

User::whereRaw([
    'age' => ['$gt' => 30, '$lt' => 40],
])->get();

User::whereRaw([
    '$where' => '/.*123.*/.test(this.field)',
])->get();

User::whereRaw([
    '$where' => '/.*123.*/.test(this["hyphenated-field"])',
])->get();

DB::collection('users')->timeout(-1)->get();

// Query Builder
DB::collection('users')
    ->where('name', 'John')
    ->update($data, ['upsert' => true]);

// Eloquent
$user->update($data, ['upsert' => true]);

DB::collection('items')
    ->project(['tags' => ['$slice' => 1]])
    ->get();

DB::collection('items')
    ->project(['tags' => ['$slice' => [3, 7]]])
    ->get();

$limit = 25;
$projections = ['id', 'name'];

DB::collection('items')
    ->paginate($limit, $projections);

DB::collection('users')
    ->where('name', 'John')
    ->push('items', 'boots');

$user->push('items', 'boots');

DB::collection('users')
    ->where('name', 'John')
    ->push('messages', [
        'from' => 'Jane Doe',
        'message' => 'Hi John',
    ]);

$user->push('messages', [
    'from' => 'Jane Doe',
    'message' => 'Hi John',
]);

DB::collection('users')
    ->where('name', 'John')
    ->push('items', 'boots', true);

$user->push('items', 'boots', true);

DB::collection('users')
    ->where('name', 'John')
    ->pull('items', 'boots');

$user->pull('items', 'boots');

DB::collection('users')
    ->where('name', 'John')
    ->pull('messages', [
        'from' => 'Jane Doe',
        'message' => 'Hi John',
    ]);

$user->pull('messages', [
    'from' => 'Jane Doe',
    'message' => 'Hi John',
]);

DB::collection('users')
    ->where('name', 'John')
    ->unset('note');

$user->unset('note');

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    public function items()
    {
        return $this->hasMany(Item::class);
    }
}

use Convenia\Mongodb\Eloquent\Model;

class Item extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    public function groups()
    {
        return $this->belongsToMany(
            Group::class, null, 'user_ids', 'group_ids'
        );
    }
}

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    public function books()
    {
        return $this->embedsMany(Book::class);
    }
}

$user = User::first();

foreach ($user->books as $book) {
    //
}

$book = Book::first();

$user = $book->user;

$book = $user->books()->save(
    new Book(['title' => 'A Game of Thrones'])
);

// or
$book =
    $user->books()
         ->create(['title' => 'A Game of Thrones']);

$book = $user->books()->first();

$book->title = 'A Game of Thrones';
$book->save();

$book->delete();

// Similar operation
$user->books()->destroy($book);

$user->books()->associate($book);
$user->save();

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    public function books()
    {
        return $this->embedsMany(Book::class, 'local_key');
    }
}

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    public function author()
    {
        return $this->embedsOne(Author::class);
    }
}

$book = Book::first();
$author = $book->author;

$author = $book->author()->save(
    new Author(['name' => 'John Doe'])
);

// Similar
$author =
    $book->author()
         ->create(['name' => 'John Doe']);

$author = $book->author;

$author->name = 'Jane Doe';
$author->save();

$newAuthor = new Author(['name' => 'Jane Doe']);

$book->author()->save($newAuthor);

$books = DB::collection('books')->get();

$hungerGames =
    DB::collection('books')
        ->where('name', 'Hunger Games')
        ->first();

DB::transaction(function () {
    User::create(['name' => 'john', 'age' => 19, 'title' => 'admin', 'email' => '[email protected]']);
    DB::collection('users')->where('name', 'john')->update(['age' => 20]);
    DB::collection('users')->where('name', 'john')->delete();
});

// begin a transaction
DB::beginTransaction();
User::create(['name' => 'john', 'age' => 19, 'title' => 'admin', 'email' => '[email protected]']);
DB::collection('users')->where('name', 'john')->update(['age' => 20]);
DB::collection('users')->where('name', 'john')->delete();

// commit changes
DB::commit();

DB::beginTransaction();
User::create(['name' => 'john', 'age' => 19, 'title' => 'admin', 'email' => '[email protected]']);

// Abort the transaction, discarding any data created as part of it
DB::rollBack();

DB::beginTransaction();
User::create(['name' => 'john', 'age' => 20, 'title' => 'admin']);

// This call to start a nested transaction will raise a RuntimeException
DB::beginTransaction();
DB::collection('users')->where('name', 'john')->update(['age' => 20]);
DB::commit();
DB::rollBack();

Schema::create('users', function ($collection) {
    $collection->index('name');
    $collection->unique('email');
});

Schema::create('users', function ($collection) {
    $collection->index(
        'username',
        null,
        null,
        [
            'sparse' => true,
            'unique' => true,
            'background' => true,
        ]
    );
});

Schema::create('bars', function ($collection) {
    $collection->geospatial('location', '2d');
});

Schema::create('bars', function ($collection) {
    $collection->geospatial('location', '2dsphere');
});

use Convenia\Mongodb\Eloquent\HybridRelations;

class User extends Model
{
    use HybridRelations;

    protected $connection = 'mysql';

    public function messages()
    {
        return $this->hasMany(Message::class);
    }
}

use Convenia\Mongodb\Eloquent\Model;

class Message extends Model
{
    protected $connection = 'mongodb';

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Convenia\Mongodb\Auth\PasswordResetServiceProvider::class,

'connections' => [
    'database' => [
        'driver' => 'mongodb',
        // You can also specify your jobs specific database created on config/database.php
        'connection' => 'mongodb-job',
        'table' => 'jobs',
        'queue' => 'default',
        'expire' => 60,
    ],
],

'failed' => [
    'driver' => 'mongodb',
    // You can also specify your jobs specific database created on config/database.php
    'database' => 'mongodb-job',
    'table' => 'failed_jobs',
],

Convenia\Mongodb\MongodbQueueServiceProvider::class,

$app->make('queue');

$app->register(Convenia\Mongodb\MongodbQueueServiceProvider::class);

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    //
}

use Convenia\Mongodb\Eloquent\HybridRelations;

class User extends Model
{

    use HybridRelations;

    protected $connection = 'mysql';
}

$books = $user->books()->sortBy('title')->get();