mongodb/laravel-mongodb
MongoDB integration for Laravel Eloquent and the Query Builder, extending the native Laravel API to work with MongoDB. Official mongodb/laravel-mongodb package (formerly jenssegers), compatible with Laravel 10.x.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require mongodb/laravel-mongodb
Add to config/app.php under providers:
MongoDB\Laravel\MongoDBServiceProvider::class,
Configuration: Publish the config file:
php artisan vendor:publish --provider="MongoDB\Laravel\MongoDBServiceProvider" --tag="mongodb-config"
Update .env with your MongoDB connection string:
MONGODB_CONNECTION=default
MONGODB_DATABASE=your_database
MONGODB_URI=mongodb://username:password@host:port/database
First Model:
Extend MongoDB\Laravel\Eloquent\Model instead of Illuminate\Database\Eloquent\Model:
use MongoDB\Laravel\Eloquent\Model;
class User extends Model
{
protected $connection = 'mongodb';
protected $collection = 'users';
protected $fillable = ['name', 'email'];
}
First Query:
$users = User::where('email', 'like', '%@gmail.com')->get();
create(), find(), update(), delete().$result = User::aggregate([
['$match' => ['age' => ['$gt' => 25]]],
['$group' => ['_id' => '$country', 'count' => ['$sum' => 1]]]
])->toArray();
php artisan mongodb:create-index users email --unique
$casts for type conversion (e.g., DateTime, Array) and $appends for computed fields:
protected $casts = [
'created_at' => 'date',
'metadata' => 'array',
];
protected $appends = ['full_name'];
hasOne, hasMany, or embedOne/embedMany:
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
$query = User::where('status', 'active')
->whereIn('role', ['admin', 'editor'])
->orderBy('name', 'asc')
->limit(10);
$text operator:
$results = User::where('name', 'text', 'John Doe')->get();
$near = [
'$near' => [
'$geometry' => ['type' => 'Point', 'coordinates' => [-73.9667, 40.78]],
'$maxDistance' => 1000,
],
];
$users = User::where('location', $near)->get();
morphTo/morphWith:
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
getAttribute() or use $accessors:
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
DB::transaction(function () {
User::create(['name' => 'John']);
Profile::create(['user_id' => $user->id]);
});
DB::retry():
DB::retry(function () {
// Transaction logic
}, 3);
Schema::create('users', function (Blueprint $collection) {
$collection->index('email', ['unique' => true]);
$collection->index('created_at');
$collection->validator(function ($validator) {
$validator->required('email')->email();
});
});
Schema::create('sessions', function (Blueprint $collection) {
$collection->index('expires_at', ['expireAfterSeconds' => 0]);
});
$users = User::select(['name', 'email'])->get();
simplePaginate() or cursor() for large datasets:
$users = User::cursor()->paginate(20);
chunk() for memory efficiency:
User::chunk(100, function ($users) {
foreach ($users as $user) {
// Process each user
}
});
use MongoDB\Laravel\Scout\MongoScoutEngine;
class User extends Model
{
public function shouldBeSearchable()
{
return true;
}
}
Queue::later(now()->addMinutes(5), new SendEmailJob($user));
mongodb session driver):
Cache::put('key', 'value', now()->addHours(1));
MongoDB\Laravel\Testing\CreatesApplication:
use MongoDB\Laravel\Testing\CreatesApplication;
class UserTest extends TestCase
{
use CreatesApplication;
public function test_create_user()
{
$user = User::create(['name' => 'Test']);
$this->assertEquals('Test', $user->name);
}
}
public function test_with_transaction()
{
$this->withoutExceptionHandling();
DB::beginTransaction();
try {
// Test logic
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
$this->fail($e->getMessage());
}
}
.env:
MONGODB_POOL_SIZE=50
MONGODB_POOL_TIMEOUT=30
$users = User::connection('mongodb')->readPreference('secondary')->get();
'retry_writes' => true,
'retry_writes_max_attempts' => 3,
$fillable/$guarded still enforce write rules.
$fillable matches your application’s write requirements. Use $casts for type safety.// Avoid:
$user = User::create(['invalid_field' => 'value']); // Throws MassAssignmentException
// Prefer:
$user = User::create(['name' => 'John']); // Valid
_id (ObjectId), but Laravel may alias it to id. Conflicts arise in queries or serializers.
$primaryKey and $keyType:class User extends Model
{
protected $primaryKey = '_id';
protected $keyType = 'string'; // or 'object' for ObjectId
}
id in queries unless aliased:// Works:
User::where('_id', $objectId)->first();
// May fail if not aliased:
User::where('id', $objectId)->first();
How can I help you explore Laravel packages today?