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"
Update .env with MongoDB connection details:
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('name', 'John')->get();
$user = User::find('507f1f77bcf86cd799439011');
create(), find(), update(), delete() just like Eloquent.$result = User::aggregate([
['$match' => ['age' => ['$gt' => 25]]],
['$group' => ['_id' => '$department', 'count' => ['$sum' => 1]]]
])->toArray();
Schema::create('users', function (Blueprint $collection) {
$collection->index('email', ['unique' => true]);
$collection->index('created_at');
});
$embedOne and $embedMany for nested structures:
class Profile extends Model
{
public function user()
{
return $this->embedOne('user');
}
}
$referenceOne and $referenceMany for relationships:
class Post extends Model
{
public function author()
{
return $this->referenceOne('User', 'author_id');
}
}
class User extends Model
{
protected $schema = [
'bsonType' => 'object',
'required' => ['name', 'email'],
'properties' => [
'name' => ['bsonType' => 'string'],
'email' => ['bsonType' => 'string', 'pattern' => '^[^@]+@[^@]+\.[^@]+$']
]
];
}
$query = User::where('active', true)
->where('age', '>', 25)
->orderBy('name', 'asc')
->limit(10);
$match, $group, $project, etc.:
$pipeline = [
['$match' => ['status' => 'active']],
['$group' => ['_id' => '$category', 'total' => ['$sum' => 1]]],
['$sort' => ['total' => -1]]
];
$result = User::aggregate($pipeline)->toArray();
Schema::create('articles', function (Blueprint $collection) {
$collection->text('title', 'content');
});
$results = Article::whereText('title', 'laravel')->get();
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
DB::transaction() for atomic operations:
DB::transaction(function () {
$user = User::find($id);
$user->update(['balance' => $user->balance - $amount]);
$transaction = Transaction::create(['user_id' => $id, 'amount' => $amount]);
});
class UserObserver
{
public function creating(User $user)
{
$user->uuid = Str::uuid()->toString();
}
}
Register in AppServiceProvider:
User::observe(UserObserver::class);
Schema::create('users', function (Blueprint $collection) {
$collection->index('email', ['unique' => true, 'sparse' => true]);
$collection->index('last_login', ['expireAfterSeconds' => 2592000]); // TTL index
});
Laravel Scout: Use MongoDB for full-text search:
class User extends Model implements Scoutable
{
public function toSearchableArray()
{
return ['name' => $this->name, 'email' => $this->email];
}
}
Configure in config/scout.php:
'driver' => 'mongodb',
Queues: Store jobs in MongoDB:
QUEUE_CONNECTION=mongodb
Use MongoQueue for job storage.
Caching: Use MongoDB as a cache driver:
CACHE_DRIVER=mongodb
API Resources: Transform MongoDB models to JSON:
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at->toDateTimeString(),
];
}
}
Testing: Use MongoDbTestCase for database testing:
use MongoDB\Laravel\Testing\MongoDbTestCase;
class UserTest extends MongoDbTestCase
{
public function test_create_user()
{
$user = User::create(['name' => 'John', 'email' => 'john@example.com']);
$this->assertEquals('John', $user->name);
}
}
ID Handling:
_id (ObjectId by default), not id. Avoid aliasing _id to id in embedded documents (use $id instead)._id is not manually set unless using a custom ID strategy:
$user = new User(['name' => 'John']);
$user->save(); // Auto-generates _id
Soft Deletes:
SoftDeletes trait is deprecated in favor of MongoDB’s native deleted_at field. Use:
use MongoDB\Laravel\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
$user->restore();
Transactions:
DB::transaction() with caution; nested transactions are not supported.Schema Validation:
try {
User::create(['name' => 123]); // Will fail validation
} catch (MongoDB\Driver\Exception\InvalidArgumentException $e) {
// Handle validation error
}
Hybrid Queries:
How can I help you explore Laravel packages today?