PHP code example of league / monga

1. Go to this page and download the library: Download league/monga 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/ */

    

league / monga example snippets



use League\Monga;

// Get a connection
$connection = Monga::connection($dns, $connectionOptions);

// Get the database
$database = $connection->database('db_name');

// Drop the database
$database->drop();

// Get a collection
$collection = $database->collection('collection_name');

// Drop the collection
$collection->drop();

// Truncate the collection
$collection->truncate();

// Insert some values into the collection
$insertIds = $collection->insert([
	[
		'name' => 'John',
		'surname' => 'Doe',
		'nick' => 'The Unknown Man',
		'age' => 20,
	],
	[
		'name' => 'Frank',
		'surname' => 'de Jonge',
		'nick' => 'Unknown',
		'nik' => 'No Man',
		'age' => 23,
	],
]);

// Update a collection
$collection->update(function ($query) {
	$query->increment('age')
		->remove('nik')
		->set('nick', 'FrenkyNet');
});

// Find Frank
$frank = $collection->findOne(function ($query) {
	$query->where('name', 'Frank')
		->whereLike('surname', '%e Jo%');
});

// Or find him using normal array syntax
$frank = $collection->find([
	'name' => 'Frank',
	'surname' => new MongoRegex('/e Jo/imxsu')
]);

$frank['age']++;

$collection->save($frank);

// Also supports nested queries
$users = $collection->find(function ($query) {
	$query->where(function ($query) {
		$query->where('name', 'Josh')
			->orWhere('surname', 'Doe');
	})->orWhere(function ($query) {
		$query->where('name', 'Frank')
			->where('surname', 'de Jonge');
	});
});

// get the users as an array
$arr = $users->toArray();

$collection->aggregate(function ($a) {
	$a->project([
		'name' => 1,
		'surname' => -1,
		'tags' => 1,
	])->unwind('tags');

	// But also more advanced groups/projections
	$a->project(function ($p) {
		$p->select('field')
			->select('scores')
			->exclude('other_field');
	})->group(function ($g) {
		$g->by(['$name', '$surname'])
			->sum('scores');
	});
});