개요
이 튜토리얼에서는 Laravel MongoDB 사용하여 프론트엔드 앱 위한 간단한 REST 백엔드를 생성합니다. 이 튜토리얼에서는 Laravel의 내장 API 라우팅 기능을 사용합니다.
전제 조건
이 튜토리얼을 시작하려면 먼저 개발 환경에 다음 소프트웨어가 설치되어 있어야 합니다.
샘플 데이터가 로드된 MongoDB Atlas cluster . 클러스터 를 만드는 방법을 학습 빠른 시작 가이드 의MongoDB 배포 만들기 단계를 참조하세요.
터미널 앱과 셸입니다. MacOS 사용자의 경우 터미널 또는 유사한 앱을 사용하세요. Windows 사용자의 경우 PowerShell을 사용하세요.
단계
Laravel MongoDB 설치합니다.
웹 서버 에서 Laravel MongoDB 실행 중인지 확인하려면 Laravel 웹사이트 에 웹 페이지를 추가합니다. 프로젝트 에서 /routes/web.php
(으)로 이동하여 다음 경로를 추가합니다.
Route::get('/info', function () { phpinfo(); });
그런 다음 셸 에서 다음 명령을 실행 애플리케이션 시작합니다.
php artisan serve
애플리케이션 실행 시작하면 http://:127.0.0.1 8000/info 로 이동하여 PHPinfo 페이지를 확인합니다. 아래로 스크롤하거나 mongodb 항목을 검색 MongoDB PHP 확장이 설치되어 있는지 확인합니다.
셸 에서 다음 명령을 실행하여 Laravel MongoDB 설치합니다.
composer require mongodb/laravel-mongodb:^5.4
MongoDB 연결을 구성합니다.
프로젝트의 config/database.php
파일 열고 다음 코드에 표시된 대로 connections
배열 업데이트 .
'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => '<connection string>', 'database' => 'db', ],
애플리케이션 실행 전에 이전 코드의 연결 문자열 자리 표시자를 연결 문자열 로 바꿔야 합니다. 연결 문자열 찾는 방법을 학습 빠른 시작 가이드 에서 연결 문자열 만들기를 참조하세요.
기본값 데이터베이스 연결을 설정하다 수도 있습니다. config/database.php
파일 상단에서 ' 기본값'를 다음과 같이 변경합니다.
'default' => 'mongodb',
이제 Laravel 애플리케이션 MongoDB cluster 의 db
데이터베이스 에 연결할 수 있습니다.
배포서버 핑 엔드포인트를 만듭니다.
다음 셸 명령을 실행하여 API 라우팅을 설정하다 합니다.
php artisan install:api
새로 만든 routes/api.php
파일 에 다음 경로를 추가합니다.
// Add the DB use statement to the top of the file. use Illuminate\Support\Facades\DB; Route::get('/ping', function (Request $request) { $connection = DB::connection('mongodb'); $msg = 'MongoDB is accessible!'; try { $connection->command(['ping' => 1]); } catch (\Exception $e) { $msg = 'MongoDB is not accessible. Error: ' . $e->getMessage(); } return ['msg' => $msg]; });
애플리케이션 다시 로드한 다음 http://:127.0.0.1 8000/api/ 핑 에 핑 메시지가 표시되는지 확인합니다.
Eloquent 모델을 생성합니다.
Laravel은 데이터베이스 백엔드를 추상화하는 ORM인 Eloquent와 통합되어 공통 인터페이스를 사용하여 다른 데이터베이스에 연결할 수 있습니다.
Eloquent는 코드와 특정 컬렉션 간의 인터페이스 제공 을 하는 Model
클래스를 제공합니다. Model
클래스의 인스턴스는 관계형 데이터베이스의 테이블 행을 나타냅니다. MongoDB 에서 문서는 컬렉션 의 문서입니다.
팁
Eloquent 모델에서 채울 수 있는 필드를 정의하여 애플리케이션 에서 문서 스키마 시행하다 하고 이름 오타와 같은 오류를 방지할 수 있습니다. 자세한 학습 은 Eloquent 모델 클래스 가이드 의 대량 할당 사용자 지정 섹션을 참조하세요.
프로젝트 루트에서 다음 명령을 실행 하여 CustomerMongoDB
이라는 Eloquent 모델을 생성합니다.
php artisan make:model CustomerMongoDB
Laravel은 /models
디렉토리 에 CustomerMongoDB
클래스를 생성합니다. 기본값 으로 모델은 default
데이터베이스 연결을 사용하지만, 클래스에 $connection
멤버를 추가하여 사용할 연결을 지정할 수 있습니다. $collection
멤버를 추가하여 컬렉션 이름을 지정할 수도 있습니다.
MongoDB Eloquent 모델에 대한 use
성명서 포함해야 합니다. 이는 _id
을 기본 키 설정하다 데 필요합니다.
CustomerMongoDB.php
파일 의 내용을 다음 코드로 바꿉니다.
use MongoDB\Laravel\Eloquent\Model; class CustomerMongoDB extends Model { // the selected database as defined in /config/database.php protected $connection = 'mongodb'; // equivalent to $table for MySQL protected $collection = 'laracoll'; // defines the schema for top-level properties (optional). protected $fillable = ['guid', 'first_name', 'family_name', 'email', 'address']; }
CRUD 작업을 수행합니다.
모델을 생성한 후 데이터 작업을 수행할 수 있습니다.
api.php
파일 에 다음 경로를 만듭니다.
Route::get('/create_eloquent_mongo/', function (Request $request) { $success = CustomerMongoDB::create([ 'guid'=> 'cust_1111', 'first_name'=> 'John', 'family_name' => 'Doe', 'email' => 'j.doe@gmail.com', 'address' => '123 my street, my city, zip, state, country' ]); });
문서 삽입한 후 다음 코드에 표시된 대로 where()
메서드를 사용하여 문서를 조회 할 수 있습니다.
Route::get('/find_eloquent/', function (Request $request) { $customer = CustomerMongoDB::where('guid', 'cust_1111')->get(); });
Eloquent를 사용하면 여러 일치 조건이 있는 복잡한 쿼리를 사용하여 데이터를 찾을 수 있습니다.
다음 경로에 표시된 데이터를 업데이트 하고 삭제 수도 있습니다.
Route::get('/update_eloquent/', function (Request $request) { $result = CustomerMongoDB::where('guid', 'cust_1111')->update( ['first_name' => 'Jimmy'] ); }); Route::get('/delete_eloquent/', function (Request $request) { $result = CustomerMongoDB::where('guid', 'cust_1111')->delete(); });
이 점 에서 MongoDB 연결 백엔드 서비스가 실행 중이지만 MongoDB 작업을 지원 위해 더 많은 기능을 제공합니다.
중첩된 데이터에 대한 작업을 수행합니다.
Laravel MongoDB 중첩 데이터에 대한 MongoDB 전용 작업을 제공합니다. 그러나 중첩된 데이터를 추가하는 것도 embedsMany()
및 embedsOne()
메서드를 사용하지 않고도 직관적입니다.
이전 단계에 표시된 대로 최상위 스키마 속성을 정의할 수 있습니다. 그러나 문서에 배열과 내장된 문서가 포함된 경우 이러한 속성을 정의하는 것이 더 복잡합니다.
모델의 데이터 구조는 PHP 에서 만들 수 있습니다. 다음 예시 에서 address
필드 는 객체 유형입니다. email
필드 는 문자열 배열 입니다.
Route::get('/create_nested/', function (Request $request) { $message = "executed"; $success = null; $address = new stdClass; $address->street = '123 my street name'; $address->city = 'my city'; $address->zip= '12345'; $emails = ['j.doe@gmail.com', 'j.doe@work.com']; try { $customer = new CustomerMongoDB(); $customer->guid = 'cust_2222'; $customer->first_name = 'John'; $customer->family_name= 'Doe'; $customer->email= $emails; $customer->address= $address; $success = $customer->save(); // save() returns 1 or 0 } catch (\Exception $e) { $message = $e->getMessage(); } return ['msg' => $message, 'data' => $success]; });
/api/create_nested/
엔드포인트에 액세스 하면 MongoDB 에 문서 생성됩니다.
{ "_id": {...}, "guid": "cust_2222", "first_name": "John", "family_name": "Doe", "email": [ "j.doe@gmail.com", "j.doe@work.com" ], "address": { "street": "123 my street name", "city": "my city", "zip": "12345" }, "updated_at": { "$date": "2025-05-27T17:38:28.793Z" }, "created_at": { "$date": "2025-05-27T17:38:28.793Z" } }
MongoDB 쿼리 API 사용합니다.
MongoDB 최적화된 쿼리를 위한 Query API 제공합니다.
collection
객체 사용하여 쿼리 빌드 을 시작할 수 있습니다. Eloquent는 Laravel이 Eloquent 쿼리 빌더의 처리 없이 데이터베이스 로 전송하는 "원시 쿼리"를 사용하여 기본 데이터베이스 의 모든 기능을 노출합니다.
다음 코드에 표시된 대로 모델에서 원시 네이티브 MongoDB 쿼리 수행할 수 있습니다.
$mongodbquery = ['guid' => 'cust_1111']; // returns a "Illuminate\Database\Eloquent\Collection" Object $results = CustomerMongoDB::whereRaw( $mongodbquery )->get();
네이티브 MongoDB 컬렉션 객체 액세스 네이티브 MongoDB 문서 또는 커서와 같은 객체를 반환하는 쿼리 수행할 수도 있습니다.
$mongodbquery = ['guid' => 'cust_1111', ]; $mongodb_native_collection = DB::connection('mongodb')->getCollection('laracoll'); $document = $mongodb_native_collection->findOne( $mongodbquery ); $cursor = $mongodb_native_collection->find( $mongodbquery );
다음 코드는 쿼리를 수행하는 여러 방법을 보여줍니다.
Route::get('/find_native/', function (Request $request) { // a simple MongoDB query that looks for a customer based on the guid $mongodbquery = ['guid' => 'cust_2222']; // Option #1 // ========= // use Eloquent's whereRaw() function // returns a "Illuminate\Database\Eloquent\Collection" Object $results = CustomerMongoDB::whereRaw( $mongodbquery )->get(); // Option #2 & #3 // ============== // use the native MongoDB driver Collection object and the Query API $mdb_collection = DB::connection('mongodb')->getCollection('laracoll'); // find the first document that matches the query $mdb_bsondoc = $mdb_collection->findOne( $mongodbquery ); // returns a "MongoDB\Model\BSONDocument" Object // to convert the MongoDB Document to a Laravel Model, use the Model's newFromBuilder() method $cust = new CustomerMongoDB(); $one_doc = $cust->newFromBuilder((array) $mdb_bsondoc); // find all documents because you pass an empty query $mdb_cursor = $mdb_collection->find(); // returns a "MongoDB\Driver\Cursor" object $cust_array = array(); foreach ($mdb_cursor->toArray() as $bson) { $cust_array[] = $cust->newFromBuilder( $bson ); } return ['msg' => 'executed', 'whereraw' => $results, 'document' => $one_doc, 'cursor_array' => $cust_array]; });
다음 코드는 updateOne()
메서드를 사용하여 문서를 업데이트 방법을 보여줍니다.
Route::get('/update_native/', function (Request $request) { $mdb_collection = DB::connection('mongodb')->getCollection('laracoll'); $match = ['guid' => 'cust_2222']; $update = ['$set' => ['first_name' => 'Henry', 'address.street' => '777 new street name'] ]; $result = $mdb_collection->updateOne($match, $update ); return ['msg' => 'executed', 'matched_docs' => $result->getMatchedCount(), 'modified_docs' => $result->getModifiedCount()]; });
다음 코드는 deleteOne()
메서드를 사용하여 문서를 삭제 방법을 보여줍니다.
Route::get('/delete_native/', function (Request $request) { $mdb_collection = DB::connection('mongodb')->getCollection('laracoll'); $match = ['guid' => 'cust_2222']; $result = $mdb_collection->deleteOne($match ); return ['msg' => 'executed', 'deleted_docs' => $result->getDeletedCount() ]; });
CRUD 작업을 수행하는 방법에 대해 자세히 학습 쓰기 작업 및 읽기 작업 가이드를 참조하세요.
집계 프레임워크 사용합니다.
집계 파이프라인 MongoDB의 집계 프레임워크 에 있는 작업 입니다. 집계 프레임워크 사용하여 실시간 보드, 빅데이터 분석 등 다양한 작업을 수행할 수 있습니다.
집계 파이프라인 각 단계의 출력이 다음 단계의 입력이 되는 여러 단계로 구성됩니다. 이 단계에서는 sample_mflix
Atlas 샘플 데이터 세트의 를 사용합니다. Laravel을 사용하면 동일한 앱 에서 여러 MongoDB 데이터베이스에 액세스 할 수 있으므로 sample_mflix
데이터베이스 연결을 에 추가합니다.database.php
'mongodb_mflix' => [ 'driver' => 'mongodb', 'dsn' => env('DB_URI'), 'database' => 'sample_mflix', ],
다음으로, /aggregate/
API 엔드포인트를 생성하고 집계 파이프라인 정의하여 movies
컬렉션 에서 데이터를 조회 , 각 장르의 평균 영화 평점을 계산하고, 목록을 반환합니다.
Route::get('/aggregate/', function (Request $request) { $mdb_collection = DB::connection('mongodb_mflix')->getCollection('movies'); $stage0 = ['$unwind' => ['path' => '$genres']]; $stage1 = ['$group' => ['_id' => '$genres', 'averageGenreRating' => ['$avg' => '$imdb.rating']]]; $stage2 = ['$sort' => ['averageGenreRating' => -1]]; $aggregation = [$stage0, $stage1, $stage2]; $mdb_cursor = $mdb_collection->aggregate( $aggregation ); return ['msg' => 'executed', 'data' => $mdb_cursor->toArray() ]; });
Laravel MongoDB 모델에서 직접 유형이 안전한 집계 파이프라인을 빌드 할 수 있는 애그리게이션 빌더 를 제공합니다. 애그리게이션을 수행하려면 집계 빌더를 사용하는 것이 좋습니다.
결론
이 튜토리얼에서는 Laravel과 MongoDB 사용하여 프론트엔드 웹 애플리케이션 에 백엔드 서비스를 생성하는 방법을 학습했습니다. 이 튜토리얼에서는 문서 모델 사용하여 데이터베이스 효율성 과 확장성 개선하는 방법도 보여줍니다. 문서 모델 MongoDB 쿼리 API 와 함께 사용하면 다운타임을 줄이고 더 나은 앱을 만들 수 있습니다.
이 튜토리얼의 전체 코드는 Github 의 Laravel-mongodb-tutorial 리포지토리 에서 액세스 할 수 있습니다.
Laravel MongoDB 문서의 나머지 부분을 살펴보고 Laravel MongoDB의 기능에 대해 자세히 학습 .