Jens Segers on Aug 20 2013

Combining Laravel and MongoDB

Unfortunately, Laravel 4 has no native support for Mongo databases. Once I started searching for open source Mongo packages on GitHub, I was disappointed that not one package was able to seamlessly integrate a Mongo database driver into Laravel 4. Every single package I found had an entirely different interface for the Query Builder and Eloquent models, which meant that I had to rewrite all of my existing code, just because I wanted to use a different database driver.

Laravel 4 and MongoDB

Therefor, I decided to write one myself, which is now called Moloquent by the community. The package I wrote depends on the existing Laravel 4 database component and extends the original classes. This means I am forced to respect the original methods and interfaces. Because most of the query translation is done by the Query Builder, a lot of Eloquent methods just work without having to modify the actual class.

After installing the package using composer, you only need to register a service provider that will add the Mongo database driver as an extension with the original database manager. More detailed installation instructions and documentation can be found at github.com/jenssegers/Laravel-MongoDB. Some functionality may not be working at this moment, so feel free to contribute.


Comments

generaltester7 6 months ago

I am using laravel version 5.5.40 and database mongodb. I have found two libraries Moloquent and https://github.com/jenssegers/laravel-mongodb. I am confused that which is the best library for my laravel and mongo website. Is both the same or subset of other?


stardesign041 7 months ago

Please resolve this asap Errror F:\xampp\htdocs\automobile\application>composer require jenssegers/mongodb Using version ^3.4 for jenssegers/mongodb ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

Problem 1

  • Conclusion: remove laravel/framework v5.5.40
  • Conclusion: don't install laravel/framework v5.5.40
  • jenssegers/mongodb v3.4.0 requires illuminate/database ^5.6 -> satisfiable by illuminate/database[v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6 .14, v5.6.15, v5.6.16, v5.6.17, v5.6.19, v5.6.2, v5.6.20, v5.6.3, v5.6.4, v5.6.5 , v5.6.6, v5.6.7, v5.6.8, v5.6.9].

stardesign041 7 months ago

Php 7 with laravel 5.5.40 mongo db laravel provider issue

Errror F:\xampp\htdocs\automobile\application>composer require jenssegers/mongodb Using version ^3.4 for jenssegers/mongodb ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

Problem 1

  • Conclusion: remove laravel/framework v5.5.40
  • Conclusion: don't install laravel/framework v5.5.40
  • jenssegers/mongodb v3.4.0 requires illuminate/database ^5.6 -> satisfiable by illuminate/database[v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6 .14, v5.6.15, v5.6.16, v5.6.17, v5.6.19, v5.6.2, v5.6.20, v5.6.3, v5.6.4, v5.6.5 , v5.6.6, v5.6.7, v5.6.8, v5.6.9].

Dhanya 1 year ago

Helo, How can we insert multiple documents ? Is InsertM any works in this Jessenger Mongo version?


Alessandro 1 year ago

Hello Jens, I'm using your package Jessenger for Laravel, unfortunately I get an error when I try to communicate with my DB.

FatalThrowableError in Client.php line 81: Class 'MongoDB\Driver\Manager' not found

I'm using PHP version 7.1, Laravel 5.4.x and the latest commit of Jessenger. I've already updated my PHP.ini and installed PHP drivers for MongoDB. What could it be?


jshetty 2 years ago

Hi Can you Tell me How can i Convert Mongodb date in Date format.

I am getting Timestamp.

Find your solution


Antonio Sánchez 2 years ago

Hey Jens,

you are awesome, like this package.

I'm definitely not going back to SQL after trying MongoDB. It works really great with Laravel thanks to your package.

Thanks.


Kshitiz 2 years ago

$arr = StudentMark::join('students', 'students.id','=','student_marks.student_id') ->select(array('student_marks.id',DB::raw('CONCAT(students.name, " ", students.surname, " (", students.index,") ") AS student')))->get();

Here I am trying to use concat function but laravel throughs an error {"error":{"type":"ErrorException","message":"Illegal offset type","file":".....vendor\jenssegers\mongodb\src\Jenssegers\Mongodb\Query\Builder.php","line":240}} Can you please help me out with this. My idea is to add a "like" query with the combinations or two columns. Please help me out.


test4rvtech 2 years ago

{ "_id" : ObjectId("561a8f3bd3783d41048b4686"),

"friends" : [ { "id" : "562dcadbd3783d69048b4894", "status" : "waiting", "way" : "incoming" }, { "id" : "56b1db63fd7851555e8b4579", "status" : "approved", "way" : "outgoing" } ], }

How can I query User Object which has Id = '561a8f3bd3783d41048b4686' & friends.id = 562dcadbd3783d69048b4894 & status=waiting

This is critical, please answer. Thanks


Ryan Kang 2 years ago

@Jens Segers I am setting my default db to mysql and mongodb to a second database.

I am getting the error below when running my script. Please see below.

Argument 1 passed to Jenssegers\Mongodb\Query\Builder::__construct() must be an instance of Jenssegers\Mongodb\Connection, instance of Illuminate\Database\MySqlConnection given, called in /var/www/html/blog/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Eloquent/Model.php on line 525 and defined

Please see my model and controller setup below:

model:

namespace App; use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Account extends Eloquent { protected $conection = 'mongodb'; protected $collection = 'accounts'; protected $fillable = ['name', 'email']; }

controller:

use App\Account;

class ProjectController extends Controller { public funtion process(Account $account) { .... for($i=0;$i$headers[$i] = $rv[$i]; } $account->save(); } }

It would be appreciated if you could shine some light over here...

Thanks in advance.


bkpandeymca 2 years ago

Jens, When you are going to build DBRef in the Laravel mongoDB ORM, without this maintaining integrity is tough here.


Linda 2 years ago

Hey there,I don't know if you'll ever read it since it's and old post, but I didn't find any other way to contact you, so here it is:First, tnkhas for this great library, I really like to work with codeigniter and this library is helping alot!Secondly, in the latest version I found a little bug in the method create_dbref , line 1409 (Mongo_db.php):return (array) MongoDBRef::get($this->db, $obj);But it should be something like this:return (array) MongoDBRef::create($collection, $id, $db);


Nagesh 3 years ago

If I want to merge two collection how can I do that ? Assume I have user list in one collection and user details in another so, how can I fetch all details?


Rodrigo 3 years ago

Laravel 5 supports % 100 ??


Renato Becker 3 years ago

Hi Jens

How do I filter results aggregates ? example : I want to list only states that the larger population than 1,000,000 ..

Natively would be like:

db.geo_cities.aggregate([ {$group:{ _id:"$properties.sigla", total_count:{ $sum:1}}}, { $match: {total_count:{ $gt:200}}} ])

Thanks!


edertonu 3 years ago

Hi Jens Segers, add your package to my application, but to create a model have the following error: Class 'Jenssegers \ MongoDB \ MongodbServiceProvider' not found, could you help me solve it?


Mohammed Shalash 3 years ago

Typo mistake "The unique validation rule to exclude the current record" the file name is
(laravel basefolder)/vendor/laravel/framework/src/illuminate/Validation/Validator.php Thanks


Mohammed Shalash 3 years ago

No No it is working ok please ignore the prev comment and rest assured the solution given is working sorry for any inconvenience.

The unique validation rule to exclude the current record (I should say document ...LOVE LARAVEL, love mongo db, love jessegers mongodb laravel adoption, most of all love my Rad4PHP CRUD generator rad4php.com). I have sorted this problem as follows: (please note this workaround is ok for MongoDB only) edit (Laravel base folder)/vendor/laravel/framework/src/illuminate/Validation.php change at line 1009: $idColumn = isset($parameters[3]) ? $parameters[3] : 'id'; to $idColumn = isset($parameters[3]) ? $parameters[3] : '_id';

Since mongodb uses _id for id field and not id as in MySql and other databases. I have tested this and works perfect with my Rad4PHP CRUD generator (www.rad4php.com)

===========


Mohammed Shalash 3 years ago

Unfortunately the work around the unique rule to exclude the current document (record) just posted has broken the unique rule in the insert new document. I am checking another solution to rectify this.


Mohammed Shalash 3 years ago

The unique validation rule to exclude the current record (I should say document ...love mongo db, love jessegers mongodb laravel adoption, most of all love my Rad4PHP cRUD generator rad4php.com). I have sorted this problem as follows: (please note this workaround is ok for MongoDB only) edit (laravel bas folder)/vendor/laravel/framework/src/illuminate/Validation.php change at line 1009: $idColumn = isset($parameters[3]) ? $parameters[3] : 'id'; to $idColumn = isset($parameters[3]) ? $parameters[3] : '_id';

Since mongodb uses _id for id field and not id as in MySql and other databases. I have tested this and works perfect with my Rad4PHP CRUD generator (www.rad4php.com)


Mohammed Shalash 3 years ago

This is very good job I wanted to use it on my Rad4PHP CRUD (www.rad4php.com) scaffolding generator, while testing the usage I come across problem in validation when updating and checking for unique validation attribute it errors to field value already taken (it does not exclude the current record from this check): e.g $validator=Validator::make(Input::all(),array( 'username' =>'required|unique:users,username,'.$id, 'email' =>'required|unique:users,email,'.$id, 'password' =>'required', 'repassword' =>'required|same:password' )); I do not have this problem on MySql only MongoDB, Any advise and suggestion to resolve it highly appreciated


Tanbir Hasan 4 years ago

Can't get it to work, followed the instructions on GitHub and changed the migration's scheme but if I run php artisan migrate only an exception is thrown exception trace:

[ErrorException] Undefined index: result

Exception trace: () at /Users/afeldmann/Dev/Trademachines/PLAYGROUND/laravel_test/laravel_test/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Builder.php:154

What is the problem?

Do you have any authentication system using Laravel-mongodb ?


Mark 4 years ago

I could use mysql and mongodb on the same project?


Rajiv Croos 4 years ago

@Jens Segers I wonder whether this orm supports adding user defined fields on the fly. Eg. if my Model classs has 2 string variables and through the User Interface if we allow user to add another custom field to the same model is it possible with this ORM and how do we achieve it. Thank you.


Arian 4 years ago

I get an error after installing and configuring : Class db does not exist


Mark Lewis 4 years ago

It seems very type sensitive. It would be great to have some methods to automatically detect dates and convert them to Mongo Data objects, as well as at least floats and integers when inserting. And when doing lookups do the integer conversion as well. Otherwise it seems like almost everything becomes a string.


jerik 4 years ago

Try to find and delete example, but had no luck. How do I delete a document, is it like that: $users = User::where('active', true)->distinct('name')->delete(); ?


Mike Patek 4 years ago

Wanted to mention that I ran into the same 'Undefined index: result' issue as Andreas. I was able to fix by uninstalling mongodb server, and installing the latest version according to this.


Jens Segers 4 years ago

@Stefan, sure you can, just like in Eloquent.


Stefan Neuser 4 years ago

How can i update an document by id?


Jens Segers 5 years ago

@Andreas, can you create an issue on github with code examples?


Andreas Feldmann 5 years ago

Can't get it to work, followed the instructions on GitHub and changed the migration's scheme but if I run php artisan migrate only an exception is thrown exception trace:

[ErrorException]
Undefined index: result

Exception trace: () at /Users/afeldmann/Dev/Trademachines/PLAYGROUND/laravel_test/laravel_test/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Builder.php:154

seems like $results is empty but can't figure out why, mongo seems to be running fine.


Jens Segers 5 years ago

@gerome, I got it working in the tests without the actual Laravel application.


gerome 5 years ago

Thanks for this interesting package - great work ! I do use eloquent, but not laravel : i'm using the standalone illuminate/database package : https://github.com/illuminate/database

Is there any way to use your mongo implementation of eloquent outside laravel ? TIA



Max 5 years ago

How to update an specific item in array, ? i use this , but do not work DB::collection($mongoTable)->where("channel",intval($id))->where("devices.id",Input::get("device"))->update(array('devices.$.enabled', 1));


Trea Hauet 5 years ago

Jens, No worries! Thanks for getting back to me!


Jens Segers 5 years ago

@Trea, sorry that is not possible at this moment.


Trea Hauet 5 years ago

Hi Jens,

I'm wondering about nested values and mutators. Is there any way to use the existing Eloquent mutators on nested values? Hopefully I'm missing something obvious. Thank you for your hard work!

Best, Trea


Louis 5 years ago

@Jens Segers: ... and it is ! Thanks !


Jens Segers 5 years ago

@Louis, update to the latest version, it should be fixed :)


Louis 5 years ago

I'm a bit confused with how to configure migrations; if I use mongodb as the default connection then issue

php artisan migrate:install

I get an error in DatabaseMigrationRepository (line 124) about the ->string method not existing.


Tom 5 years ago

Excellent, I got it working with array("image_checksum" => 1, "username" => 1), array("unique" => true) as the two parameters.


Jens Segers 5 years ago

@Tom, try passing the same array as you would with http://php.net/manual/en/mongocollection.ensureindex.php


Tom 5 years ago

Ah okay. I tried the following in my laravel migrations:

Schema::create("user_image_vote", function(Blueprint $collection) { $collection->index(array("username", "image_checksum")); });

And php artisan comes back with the following error:

localhost:27017: can only have 1 index plugin / bad index key pattern

Any insight into this?


Jens Segers 5 years ago

@Tom, there is! Just pass an array of columns!


Tom 5 years ago

Hello Jens, any chance in the schema builder of support for composite keys?

Keep up the great work!


Jens Segers 5 years ago

@JB, that is the native PHP class: http://www.php.net/manual/en/mongo.installation.php


Jens Segers 5 years ago

@Gareth Daine, I did not try it yet :)


Gareth Daine 5 years ago

Looks like a great package. Does this work well with Cartalyst Sentry?


JB 5 years ago

I followed the setup on the github readme.

However, I run into this error:

Class 'MongoClient' not found

Where is this class supposed to be coming from? Do I need to download this separately?

Thanks,

JB


Awidarto 5 years ago

ah, i see... thanks for the pointer, honestly I'm not familiar with Schema and RDBMS support in Laravel, been using Mongo with it since I started using Laravel 3 ( using bundle, and then LMongo on 4 ). Once again, thanks for this great library, this is the most Laravel-ish solution so far, Taylor should adopt this into the official package for Mongo support, IMO.


Jens Segers 5 years ago

@Awidarto, the Schema builder is mainly used to create or delete collections and define indexes. Read more about the functionality on https://github.com/jenssegers/Laravel-MongoDB#schema


Awidarto 5 years ago

Love it, works out of the box with standard Auth driver, one thing I still can have wrapped on my head is Schema, what does it do actually ? I believe it is not like Schema in RDBMS ( MySQL or Sqlite ), as Mongo doesn't have predefinition of structure ... auto hydration perhaps ?


Jens Segers 5 years ago

@Jake; give it a try. The main thing that has not been implemented yet, are the "advanced" relations. Other than that, most of the functionality you will be using is ready and tested.


Jake 5 years ago

Hey Jens, how close to "production-ready" would you say this is?


Mick Davies 5 years ago

Hey Jens, I've implemented your package but I just wanted to know the best way (if at all possible) to get to nested arrays but in an object style way?

such as $property->address; as well as $property->details->bedrooms; Currently eloquent is giving me back a property but the nested items which I want to be objects are actually standard arrays.


Jens Segers 5 years ago

@rovan; they should. Check out https://github.com/jenssegers/Laravel-MongoDB#schema


rovan 5 years ago

does migrations work with mongodb?


Jens Segers 5 years ago

@Laurent, I am using 4.0.x because 4.1.x is still under development. It is not possible to use the same code for both versions at this moment.


Aaron Bullard 5 years ago

Awesome package. Looking forward to trying it out!


Laurent 5 years ago

Thanks for the nice package! BTW Laravel 4.1.x is out, when I install my project with composer, it fails because your package requires some laravel "4.0.x" (in your composer.json file). Could you update that? Cheers!


Jens Segers 5 years ago

@Daniel, lmongo does not respect the original Eloquent and Query Builder methods. I explained this in the first paragraph. Also, I register a database driver instead of forcing users to use a different DB facade.


Daniel Gafitescu 5 years ago

What was wrong with https://github.com/navruzm/lmongo