Simple and swift MongoDB abstraction.

Related tags

Caching monga
Overview

Monga

Latest Version on Packagist Software License Build Status Total Downloads

A simple and swift MongoDB abstraction layer for PHP 5.4+

What's this all about?

  • An easy API to get connections, databases and collections.
  • A filter builder that doesn't make your mind go nuts.
  • All sorts of handy update functions.
  • An abstraction for sorting single results.
  • GridFS support for a Mongo filesystem.
  • Easy aggregation and distinct values.

Vision

Monga was created with the acknowledgment of the MongoDB PHP package already being pretty awesome. That's why in a lot of cases Monga is just a simple wrapper around the MongoDB classes. It provides some helpers and helps you set up queries using a query builder. Which you can also choose not to use! Everything will still work accordingly. During the development, a lot of planning has gone into creating a nice streamlined API that closely follows the MongoDB base classes, while complementing existing query builders for SQL-like databases.

Install

Via Composer

$ composer require league/monga

Usage

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();

Aggregation

A big part of the newly released MongoDB pecl package is aggregation support. Which is super easy to do with Monga:

$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');
	});
});

Contributing

Please see CONTRIBUTING and CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Documentation

    Documentation

    Is there published documentation for this library? I'm having a hell of a time figuring out some basic things like, for example, using an operator other than the = sign in a query. i.e. Find all items in a collection where the timestamp is less than now.

    Anyway are there docs or am I going rogue code diving?

    (Great library, so far! Thanks for putting this out there)

    opened by webkenny 5
  • collection find function

    collection find function

    When I was trying to fetch all documents from one of my collection without where clause and with fields i want, it always returned an empty array. I checked and found that issue in Collection.php line number 317 and 318.

    opened by shahmanthan9 5
  • Fix all the things.

    Fix all the things.

    • Update src/ to be PSR-2 compliant.
    • Replace deprecated safe option w/ write concern.
    • Remove/replace usage of deprecated MongoClient::connected property.
    • Replace deprecated Mongo class w/ MongoClient.
    • Update Travis CI config to use PHPUnit 3.7.*... (default Travis PHPUnit version has changed since last time Travis ran...)

    This being said... with replacing the safe value from a boolean, to 0 or 1, it's a BC break. Not sure how to handle this... there's only a master branch here... heh. Pull and tag a new minor version or something? Also, let me know what you guys think / find.

    opened by bcrowe 5
  • Fix and Update

    Fix and Update

    I just clean up my local branch and re-commit my fixes again. I am more a bitbucket user rather than github, please let me know if I missed anything.

    Happy coding :+1:

    T.L

    opened by maxtrunk 4
  • Need help on PushAll

    Need help on PushAll

    Hey everyone,

    I am having this "not write to database" issue with pushAll. Can anyone point me a right direction where I am doing wrong with the following code?

    $result = $this->collection('my_collection') ->update(function ($query) { $query->where($where)->pushAll( 'my_field', $push_query_array ); });

    $result is return as TRUE.

    Big Thanks.

    opened by maxtrunk 3
  • Retry on master write failure

    Retry on master write failure

    Silly github lost the rest!

    Recovering failed connections with replicasets and failover is fairly easy to centralize

    But there can be some pretty crazy latency with the rediscovery. If the driver connects to a secondary and later tries a write it will fail.

    In this case the write should really be retried. Sure you could do this by wrapping monga in another class (sigh) but it would be far more elegant to simply catch MongoCursorExceptions and look for the "not master" failure for inserts/saves and retry

    opened by auroraeosrose 3
  • Weird syntax for calling method

    Weird syntax for calling method

    I'm having hard time figuring out why this

    public function andWhereNot($field, $value)
    {
        return call_user_func_array([$this, 'whereNot'], func_get_args());
    }
    

    has been used instead of

    public function andWhereNot($field, $value)
    {
        return $this->whereNot($field, $value);
    }
    

    which would have been, imho, way more explicit and readable. Is there any particular reason? I'd be willing to refactor all the call_user_func_* usage to direct method calls (of course when it make sense) if you guys will accept a PR for this.

    opened by ftassi 2
  • Tests failing on php 5.6

    Tests failing on php 5.6

    Hi guys, running the suite tests against php 5.6 I'm getting 2 errors

    There were 2 failures:
    
    1) ConnectionTests::testHasDatabase
    Failed asserting that false is true.
    
    /Users/ftassi/workspace/monga/tests/ConnectionTests.php:49
    
    2) ConnectionTests::testListDatabases
    Failed asserting that an array contains 'admin'.
    
    /Users/ftassi/workspace/monga/tests/ConnectionTests.php:71```
    
    Basically both due to a non existent database `admin`. I'm not quite sure where this databases is created and why it should be there. What am I missing? 
    
    Here is my mongo version:
    
    

    ➜ monga git:(master) ✗ php --ri mongo | grep Version Version => 1.6.7 ➜ monga git:(master) ✗ mongod --version db version v3.0.3

    opened by ftassi 2
  • Multiple remove (not issue)

    Multiple remove (not issue)

    I want to remove every document which have same id. My code is

    $comments = $this->mongo->collection(Collections::COMMENTS);
            $comments->find(function ($query) use ($check) {
                $query->where('cid', $check)->remove()->multiple();
            });
    

    is this type of use correct? Thanks in advance...

    opened by rhnkyr 2
  • Query builders usable by Collection methods

    Query builders usable by Collection methods

    This PR allows Query\Builder instances to be passed to various Collection methods:

    • find allows a Query\Find instance to be passed as the first parameter
    • remove allows a Query\Remove instance to be passed as the first parameter
    • update allows a Query\Update instance to be passed as the first parameter

    P.S. Apologies if this PR "sucks" in any way, this is actually breaking my PR virginity. Feedback, both positive and/or negative, is greatly appreciated.

    opened by georgeholt 2
  • Seeder

    Seeder

    Love this library so far but I have a need to do some random seeding of data for an API I am putting together. Is there a recommended approach to do that with monga or would it be worth my rolling a plugin for fzaninotto/Faker?

    opened by webkenny 2
Releases(1.2.4)
  • 1.2.4(Feb 29, 2016)

  • 1.2.3(Dec 8, 2015)

  • 1.2.2(Nov 20, 2015)

  • 1.2.1(Oct 20, 2015)

    • Added CONDUCT.md
    • Added the ability to pass in SSL context options to connections.
    • Added the ability to pass query objects into collection methods.
    • Updated README.md
    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Sep 22, 2015)

    • Fixed an issue where MongoCollection::find() relied on both $query->where() and $query->select() to be called in order for the find()s arguments to be in the correct order.

    Applications that may have code that relied on the mismatched order will want pin/continue using 1.1.0 or lower.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Feb 15, 2015)

  • 1.0.6(Feb 12, 2015)

    Added the ability to set a maximum number of retries for "not master" MongoCursorExceptions within CRUD operations in the Collection class. Augments issue https://github.com/thephpleague/monga/issues/8. Defaults to 1 retry as previously implemented.

    Source code(tar.gz)
    Source code(zip)
  • 1.0.5(Oct 29, 2014)

  • 1.0.4(Oct 25, 2014)

    • The safe option now injects a w option instead of deprecated safe option.
    • Remove usage of deprecated Mongo class in favor of MongoClient.
    • Fix PSR2 coding standards.
    • General repository cleanup.
    Source code(tar.gz)
    Source code(zip)
Owner
The League of Extraordinary Packages
A group of developers who have banded together to build solid, well tested PHP packages using modern coding standards.
The League of Extraordinary Packages
Simple cache abstraction layer implementing PSR-16

sabre/cache This repository is a simple abstraction layer for key-value caches. It implements PSR-16. If you need a super-simple way to support PSR-16

sabre.io 48 Sep 9, 2022
Zend Framework cache backend for MongoDB

Zend_Cache_Backend_Mongo Author: Anton Stöckl About Zend_Cache_Backend_Mongo is a Zend Framework Cache Backend for MongoDB. It supports tags and autoc

Anton Stöckl 12 Feb 19, 2020
A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Desarolla2 Cache A simple cache library, implementing the PSR-16 standard using immutable objects. Caching is typically used throughout an applicatito

Daniel González 129 Nov 20, 2022
A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Desarolla2 Cache A simple cache library, implementing the PSR-16 standard using immutable objects. Caching is typically used throughout an applicatito

Daniel González 129 Nov 20, 2022
Simple cache

Simple cache

Róbert Kelčák 3 Dec 17, 2022
Simple Yet Powerful PHP Caching Class

The PHP high-performance object caching system ever. phpFastCache is a high-performance, distributed object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. phpFastCache dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful

Khoa Bui 28 Aug 19, 2022
Simple artisan command to debug your redis cache. Requires PHP 8.1 & Laravel 9

?? php artisan cache:debug Simple artisan command to debug your redis cache ?? Installation You can install the package via composer: composer require

Juan Pablo Barreto 19 Sep 18, 2022
DataLoaderPhp is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

DataLoaderPHP is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

Webedia - Overblog 185 Nov 3, 2022
CLI App and library to manage apc & opcache.

CacheTool - Manage cache in the CLI CacheTool allows you to work with APCu, OPcache, and the file status cache through the CLI. It will connect to a F

Samuel Gordalina 1.4k Jan 3, 2023
PHP cache library, with adapters for e.g. Memcached, Redis, Couchbase, APC(u), SQL and additional capabilities (e.g. transactions, stampede protection) built on top.

Donate/Support: Documentation: https://www.scrapbook.cash - API reference: https://docs.scrapbook.cash Table of contents Installation & usage Adapters

Matthias Mullie 295 Nov 28, 2022
A thin PSR-6 cache wrapper with a generic interface to various caching backends emphasising cache tagging and indexing.

Apix Cache, cache-tagging for PHP Apix Cache is a generic and thin cache wrapper with a PSR-6 interface to various caching backends and emphasising ca

Apix 111 Nov 26, 2022
A flexible and feature-complete Redis client for PHP.

Predis A flexible and feature-complete Redis client for PHP 7.2 and newer. ATTENTION: you are on the README file of an unstable branch of Predis speci

Predis 7.3k Jan 3, 2023
Boost the speed of Kirby by having content files of pages cached, with automatic unique ID, fast lookup and Tiny-URL.

?? Kirby3 Boost ⏱️ up to 3x faster content loading ?? fastest page lookup and resolution of relations Boost the speed of Kirby by having content files

Bruno Meilick 41 Jan 8, 2023
Caching implementation with a variety of storage options, as well as codified caching strategies for callbacks, classes, and output

laminas-cache Laminas\Cache provides a general cache system for PHP. The Laminas\Cache component is able to cache different patterns (class, object, o

Laminas Project 69 Jan 7, 2023
A fast, light-weight proxy for memcached and redis

twemproxy (nutcracker) twemproxy (pronounced "two-em-proxy"), aka nutcracker is a fast and lightweight proxy for memcached and redis protocol. It was

Twitter 11.7k Jan 2, 2023
The cache component provides a Promise-based CacheInterface and an in-memory ArrayCache implementation of that

Cache Async, Promise-based cache interface for ReactPHP. The cache component provides a Promise-based CacheInterface and an in-memory ArrayCache imple

ReactPHP 330 Dec 6, 2022
Graphic stand-alone administration for memcached to monitor and debug purpose

PHPMemcachedAdmin Graphic stand-alone administration for memcached to monitor and debug purpose This program allows to see in real-time (top-like) or

Cyrille Mahieux 249 Nov 15, 2022
A library providing platform-specific user directory paths, such as config and cache

Phirs A library providing platform-specific user directory paths, such as config and cache. Inspired by dirs-rs.

Mohammad Amin Chitgarha 7 Mar 1, 2022