Simple and swift MongoDB abstraction.

Related tags

NoSQL 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
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
Simple and swift MongoDB abstraction.

Monga 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 fi

The League of Extraordinary Packages 330 Nov 28, 2022
Php mongodb admin, use new mongodb extension.

EasyMongo EasyMongo is a Mongodb web management application. This project is based on iwind/RockMongo, uses the latest mongodb-extension + mongo-php-l

Meng Wang 8 Oct 31, 2022
A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

Jan Schädlich 69 Dec 18, 2022
Simple MongoDB API for PHP!

SimpleMongo SimpleMongo is a simple API for MongoDB, written in PHP. How to use? First of all, copy SimpleMongo.php into your project and fill the fir

AlicanCopur 9 Jul 19, 2021
A simple, proof-of-concept Laravel blog application powered by a MongoDB ORM.

Mongoblog A simple, proof-of-concept Laravel blog application powered by a MongoDB ORM. Separated API and front-end This is a RESTful application, who

Jayps 4 Nov 8, 2022
:zap: Simple Cache Abstraction Layer for PHP

⚡ Simple Cache Class This is a simple Cache Abstraction Layer for PHP >= 7.0 that provides a simple interaction with your cache-server. You can define

Lars Moelleken 27 Dec 8, 2022
:gem: Simple MySQLi Abstraction Layer + Doctrine/DBAL support

?? Simple MySQLi Class This is a simple MySQL Abstraction Layer compatible with PHP 7+ that provides a simple and secure interaction with your databas

Lars Moelleken 40 Sep 5, 2022
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
Super-simple, minimum abstraction MailChimp API v3 wrapper, in PHP

MailChimp API Super-simple, minimum abstraction MailChimp API v3 wrapper, in PHP. I hate complex wrappers. This lets you get from the MailChimp API do

Drew McLellan 2k Dec 22, 2022
A super simple abstraction to make creating a custom Taxonomies in WordPress a breeze

A super simple abstraction to make creating a custom Taxonomies in WordPress a breeze

Joe Grant 2 Apr 5, 2022
Orm is a simple database abstraction layer that supports postgresql.

Orm What is it Orm is a simple database abstraction layer that supports postgresql. Welcome to join us or star us for encouragement. Requires php 8.1

null 2 Sep 28, 2022
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

Jens Segers 6.3k Jan 5, 2023
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

Jens Segers 6.3k Jan 7, 2023
MongoDB ORM that includes support for references,embed and multilevel inheritance.

Introduction Features Requirements Installation Setup Database Basic Usage - CRUD Relationship - Reference Relationship - Embed Collection Inheritance

Michael Gan 202 Nov 17, 2022
Dockerized PHP development stack: Nginx, MySQL, MongoDB, PHP-FPM, HHVM, Memcached, Redis, Elasticsearch and RabbitMQ

PHP Dockerized Dockerized PHP development stack: Nginx, MySQL, MongoDB, PHP-FPM, HHVM, Memcached, Redis, Elasticsearch and RabbitMQ PHP Dockerized giv

Kasper Isager Dalsgarð 1.1k Dec 30, 2022
MongoDB ODM. Part of @PHPMongoKit

PHPMongo ODM PHP ODM for MongoDB. ⭐ Why to use this ODM? You can easily work with document data through comfortable getters and setters instead of arr

Sokil 240 Nov 27, 2022
MongoDB PHP library

MongoDB PHP Library This library provides a high-level abstraction around the lower-level PHP driver (mongodb extension). While the extension provides

mongodb 1.5k Dec 31, 2022
Psalm Stubs for doctrine/mongodb-odm library

doctrine-mongodb-psalm-plugin A Doctrine plugin for Psalm (requires Psalm v4). Installation: $ composer require --dev runtothefather/doctrine-mongodb-

Evgeny 6 Jun 15, 2022
Eloquent MongoDB Repository Implementation

Eloquent MongoDB Repository Eloquent MongoDB Repository using nilportugues/repository as foundation, using jenssegers/mongodb. Installation Use Compos

Nil Portugués Calderó 18 Feb 12, 2022