Using Laravel Eloquent with MongoDB
Laravel provides a powerful and flexible ORM (Object-Relational Mapping) called Eloquent, which allows developers to interact with databases using an intuitive syntax. While Laravel is designed for relational databases, it also supports MongoDB through third-party packages like jenssegers/laravel-mongodb. This blog explores how to use Eloquent with MongoDB in Laravel, covering model setup, CRUD operations, advanced querying, and working with embedded documents. Additionally, we will discuss more advanced topics such as performance optimization, transactions, and best practices.
Setting Up MongoDB Models in Laravel
To use MongoDB in Laravel, you need to install the jenssegers/laravel-mongodb package:
composer require jenssegers/mongodb
Then, configure the MongoDB connection in config/database.php:
'mongodb' => [
'driver' => 'mongodb',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE', 'your_database'),
'username' => env('DB_USERNAME', ''),
'password' => env('DB_PASSWORD', ''),
'options' => [
'database' => 'admin' // Authentication database
]
],
Create a model that extends Jenssegers\Mongodb\Eloquent\Model:
use Jenssegers\Mongodb\Eloquent\Model;
class User extends Model
{
protected $connection = 'mongodb';
protected $collection = 'users';
protected $fillable = ['name', 'email', 'password', 'roles'];
}
Performing CRUD Operations with MongoDB
Create a New Document
User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password123'),
'roles' => ['admin', 'editor']
]);
Read Documents
Fetch all users:
$users = User::all();
Find a user by ID:
$user = User::find($id);
Fetch users with specific roles:
$admins = User::where('roles', 'admin')->get();
Update a Document
$user = User::find($id); $user->update(['name' => 'Jane Doe', 'roles' => ['editor']]);
Delete a Document
$user->delete();
Querying Data from MongoDB using Eloquent
Filtering Data
$users = User::where('email', 'like', '%@gmail.com%')->get();
Sorting Data
$users = User::orderBy('name', 'asc')->get();
Pagination
$users = User::paginate(10);
Using Aggregation Framework in Eloquent Queries
MongoDB’s aggregation framework is useful for complex data processing. You can use Laravel’s aggregate method:
$users = User::raw(function ($collection) {
return $collection->aggregate([
['$group' => ['_id' => '$role', 'count' => ['$sum' => 1]]]
]);
});
Working with Embedded Documents (Subdocuments)
MongoDB allows embedding subdocuments within documents. You can structure data like this:
$user = User::create([
'name' => 'Alice',
'email' => 'alice@example.com',
'address' => [
'street' => '123 Main St',
'city' => 'New York',
'zip' => '10001'
]
]);
Querying Embedded Documents
Find users based on an embedded document field:
$users = User::where('address.city', 'New York')->get();
Performance Optimization and Transactions
Indexing for Faster Queries
To improve performance, create indexes on frequently queried fields:
User::raw(function ($collection) {
return $collection->createIndex(['email' => 1]);
});
Using Transactions
MongoDB supports ACID transactions, which you can use in Laravel:
DB::transaction(function () {
User::create([...]);
Order::create([...]);
});
Best Practices
- Use Indexes to optimize query performance.
- Limit Large Queries to avoid performance issues.
- Use Transactions when modifying multiple related documents.
- Embed Documents Wisely for efficient data modeling.
Conclusion
Using Laravel Eloquent with MongoDB provides a seamless experience for developers familiar with relational databases. By leveraging Eloquent’s ORM capabilities, developers can perform efficient queries, use aggregation pipelines, and work with embedded documents in a structured way. Additionally, implementing indexing and transactions ensures performance optimization. With MongoDB’s flexibility and Laravel’s expressive syntax, building scalable applications becomes much easier.
