### Command Output Example Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/database-collection Example output showing the list of collections retrieved from the database. ```console sessions movies theaters comments embedded_movies users ``` -------------------------------- ### Install Laravel Breeze Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/application-tutorial Install the Laravel Breeze authentication package. ```bash composer require laravel/breeze --dev ``` -------------------------------- ### Start Laravel Server Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Starts the built-in PHP development server. ```bash php artisan serve ``` -------------------------------- ### Copy Environment File Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Initialize the .env file by copying the example configuration. ```sh cp .env.example .env ``` -------------------------------- ### Install Laravel Installer Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Installs the Laravel installer globally using Composer. ```bash composer global require laravel/installer ``` -------------------------------- ### Install dependencies Source: https://www.mongodb.com/docs/drivers/php-frameworks/llphant Install LLPhant, MongoDB PHP library, and Symfony dotenv via Composer. ```bash composer require theodo-group/llphant symfony/dotenv mongodb/mongodb ``` -------------------------------- ### Execute the Application Source: https://www.mongodb.com/docs/drivers/php-frameworks/llphant Command to start the PHP application from the project root directory. ```bash php index.php ``` -------------------------------- ### Install Laravel Sanctum Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/user-authentication Commands to install and publish Laravel Sanctum configuration. ```bash composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" ``` -------------------------------- ### Initialize Authentication Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/application-tutorial Run commands to generate keys, install Breeze, migrate, seed, and build assets. ```bash php artisan key:generate php artisan breeze:install php artisan migrate php artisan db:seed npm install npm run dev ``` -------------------------------- ### Install Laravel Passport Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/user-authentication Run this command from the project root to install Passport and run necessary database migrations. ```bash php artisan install:api --passport ``` -------------------------------- ### Install Laravel Scout Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/scout Run this command in the application root directory to install the Scout package. ```bash composer require laravel/scout ``` -------------------------------- ### Install Twig Bundle Source: https://www.mongodb.com/docs/drivers/php-frameworks/symfony Install the Twig template engine bundle via Composer. ```text composer require symfony/twig-bundle ``` -------------------------------- ### Install GridFS Flysystem Package Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/filesystems Install the required package via Composer before configuring the driver. ```bash composer require league/flysystem-gridfs ``` -------------------------------- ### Breeze Stack Selection Interface Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/application-tutorial Visual representation of the Laravel Breeze installation prompt. ```text ┌ Which Breeze stack would you like to install? ───────────────┐ │ > ● Blade with Alpine │ │ ○ Livewire (Volt Class API) with Alpine │ │ ○ Livewire (Volt Functional API) with Alpine │ │ ○ React with Inertia │ │ ○ Vue with Inertia │ │ ○ API only │ └──────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Start PHP Development Server Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Launch the built-in PHP web server to host the Drupal application. ```bash php -S localhost:8080 -t web ``` -------------------------------- ### Install API and define route Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Commands and configuration to enable API routes and map the store method. ```bash php artisan install:api ``` ```php use App\Http\Controllers\MovieController; // ... Route::resource('movies', MovieController::class)->only([ 'store' ]); ``` -------------------------------- ### Start Symfony Development Server Source: https://www.mongodb.com/docs/drivers/php-frameworks/symfony Launches the PHP built-in web server from the application root directory. ```bash symfony server:start ``` -------------------------------- ### Verify Composer Configuration Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started The required entry in the composer.json file after installation. ```json "mongodb/laravel-mongodb": "^5.8" ``` -------------------------------- ### Example Document Output Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/relationships Shows the resulting document structure in MongoDB collections after establishing relationships. ```json // Documents in the "planets" collection [ { _id: ObjectId('65e1043a5265269a03078ad0'), name: 'Earth', // ... space_explorer_ids: [ '65e1043b5265269a03078ad3', '65e1043b5265269a03078ad4', '65e1043b5265269a03078ad5' ], }, { _id: ObjectId('65e1043a5265269a03078ad1'), name: 'Mars', // ... space_explorer_ids: [ '65e1043b5265269a03078ad4', '65e1043b5265269a03078ad5' ] }, { _id: ObjectId('65e1043b5265269a03078ad2'), name: 'Jupiter', // ... space_explorer_ids: [ '65e1043b5265269a03078ad3', '65e1043b5265269a03078ad5' ] } ] // Documents in the "space_explorers" collection [ { _id: ObjectId('65e1043b5265269a03078ad3'), name: 'Tanya Kirbuk', // ... planet_ids: [ '65e1043a5265269a03078ad0', '65e1043b5265269a03078ad2' ] }, { _id: ObjectId('65e1043b5265269a03078ad4'), name: 'Mark Watney', // ... planet_ids: [ '65e1043a5265269a03078ad0', '65e1043a5265269a03078ad1' ] }, { _id: ObjectId('65e1043b5265269a03078ad5'), name: 'Jean-Luc Picard', // ... planet_ids: [ '65e1043a5265269a03078ad0', '65e1043a5265269a03078ad1', '65e1043b5265269a03078ad2' ] } ] ``` -------------------------------- ### Specify Multiple Hosts Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/connect-to-mongodb Example of defining multiple hosts in an array for the connection configuration. ```php 'host' => ['node1.example.com:27017', 'node2.example.com:27017', 'node3.example.com:27017'], ``` -------------------------------- ### Insert Sample Document Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/modify Initial document creation used as the basis for subsequent array modification examples. ```php Concert::create([ 'performer' => 'Mitsuko Uchida', 'genres' => ['classical', 'dance-pop'], ]); ``` -------------------------------- ### Example Output Documents Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/relationships Shows the resulting document structure in the MongoDB collections after saving the relationship. ```json // Document in the "planets" collection { _id: ObjectId('65de67fb2e59d63e6d07f8b8'), name: 'Earth', diameter_km: 12742, // ... } // Document in the "orbits" collection { _id: ObjectId('65de67fb2e59d63e6d07f8b9'), period: 365.26, direction: 'counterclockwise', planet_id: '65de67fb2e59d63e6d07f8b8', // ... } ``` -------------------------------- ### Implement AuthController Logic Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/user-authentication Example implementation of login and logout methods within an AuthController. ```php validate([ 'email' => 'required|email', 'password' => 'required', ]); if (Auth::attempt($request->only('email', 'password'))) { return response()->json([ 'user' => Auth::user(), 'message' => 'Successfully logged in', ]); } throw ValidationException::withMessages([ 'email' => ['The provided credentials are incorrect.'], ]); } public function logout() { Auth::logout(); return response()->json(['message' => 'Successfully logged out']); } } ``` -------------------------------- ### Begin and Commit a Transaction Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/transactions Use DB::beginTransaction() to start a transaction and DB::commit() to persist all changes made to the database. ```php DB::beginTransaction(); $oldAccount = Account::where('number', 223344)->first(); $newAccount = Account::where('number', 776655)->first(); $newAccount->balance += $oldAccount->balance; $newAccount->save(); $oldAccount->delete(); DB::commit(); ``` -------------------------------- ### Search Query Output Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/atlas-search Example JSON output from a search query. ```json [ { "title": "Dreaming of Jakarta", "year": 1990 }, { "title": "See You in My Dreams", "year": 1996 } ] ``` -------------------------------- ### Specify Single Host Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/connect-to-mongodb Example of defining a single host and port in the connection configuration. ```php 'host' => 'myhost.example.com:27017', ``` -------------------------------- ### Example Output Data Structure Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/relationships Shows the resulting document structure in MongoDB after saving related models. ```json // Parent document in the "planets" collection { _id: ObjectId('65dfb0050e323bbef800f7b2'), name: 'Jupiter', diameter_km: 142984, // ... } // Child documents in the "moons" collection [ { _id: ObjectId('65dfb0050e323bbef800f7b3'), name: 'Ganymede', orbital_period: 7.15, planet_id: '65dfb0050e323bbef800f7b2', // ... }, { _id: ObjectId('65dfb0050e323bbef800f7b4'), name: 'Europa', orbital_period: 3.55, planet_id: '65dfb0050e323bbef800f7b2', // ... } ] ``` -------------------------------- ### Create a Migration Class for MongoDB Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/schema-builder Example of a migration class using the MongoDB-specific Blueprint to create a collection and index. ```php index('name'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::drop('astronauts'); } }; ``` -------------------------------- ### Custom Index Definition Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/scout Example of adding custom index definitions to the config/scout.php file. ```php 'mongodb' => [ 'connection' => env('SCOUT_MONGODB_CONNECTION', 'mongodb'), 'index-definitions' => [ 'scout_movies' => [ 'mappings' => [ 'dynamic' => false, 'fields' => ['title' => ['type' => 'string']] ] ] ] ], ... ``` -------------------------------- ### Verify Bundle Configuration Source: https://www.mongodb.com/docs/drivers/php-frameworks/symfony Example of the entry in config/bundles.php to confirm the Doctrine MongoDB bundle is enabled. ```php return [ // ... Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle::class => ['all' => true], ]; ``` -------------------------------- ### Configuring Additional MongoDB Connections Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial Example configuration for adding a new MongoDB database connection in database.php. ```php 'mongodb_mflix' => [ 'driver' => 'mongodb', 'dsn' => env('DB_URI'), 'database' => 'sample_mflix', ], ``` -------------------------------- ### PHP Development Server Output Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Expected output when the PHP development server starts successfully. ```bash [Date Time] PHP 8.3.0 Development Server (http://localhost:8080) started ``` -------------------------------- ### Complete User Model Configuration Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/user-authentication A full example of a User model configured to use the MongoDB connection and table. ```php [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => 'mongodb+srv//myUser:myPass123@sample.host/', 'database' => 'sample_mflix', 'options' => [ 'w' => 'majority', ], 'driver_options' => [ 'serverApi' => 1, ], ], // ... ], ``` -------------------------------- ### Upsert Method Example Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/modify Perform a batch upsert operation to update or insert multiple documents. ```php Concert::upsert([ ['performer' => 'Angel Olsen', 'venue' => 'Academy of Music', 'ticketsSold' => 275], ['performer' => 'Darondo', 'venue' => 'Cafe du Nord', 'ticketsSold' => 300], ], 'performer', ['ticketsSold']); ``` -------------------------------- ### Example MongoDB Connection URI Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/connect-to-mongodb A standard connection string format including credentials, host, port, and query options. ```text mongodb://myUser:myPass123@localhost:27017/?w=majority&retryWrites=true ``` -------------------------------- ### Inserting and Retrieving Versioned Models Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/model-class Example of inserting documents with and without explicit schema versions and retrieving them to trigger migrations. ```php // Simulates a document in the collection with schema version 1 Planet::insert([ [ 'name' => 'WASP-39 b', 'type' => 'gas', 'schema_version' => 1, ], ]); // Saves a document with no specified schema version $saturn = Planet::create([ 'name' => 'Saturn', 'type' => 'gas', ]); // Retrieves both models from the collection $planets = Planet::where('type', 'gas') ->get(); ``` -------------------------------- ### Initialize Project Directory Source: https://www.mongodb.com/docs/drivers/php-frameworks/llphant Create the source directory and the DocumentSearchService file on macOS or Linux. ```bash mkdir -p src touch src/DocumentSearchService.php ``` -------------------------------- ### Initialize index file Source: https://www.mongodb.com/docs/drivers/php-frameworks/llphant Create the initial index.php file on macOS or Linux. ```bash touch index.php ``` -------------------------------- ### Set up API routing Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial Initialize API routing for the project. ```bash php artisan install:api ``` -------------------------------- ### Enable and Retrieve MongoDB Query Logs Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query/query-logging Use the enableQueryLog method to start tracking queries and getQueryLog to retrieve the stored logs in memory. ```php DB::connection('mongodb')->enableQueryLog(); Movie::where('title', 'Carrie')->get(); Movie::where('year', '<', 2005)->get(); Movie::where('imdb.rating', '>', 8.5)->get(); $logs = DB::connection('mongodb')->getQueryLog(); foreach ($logs as $log) { echo json_encode($log, JSON_PRETTY_PRINT) . PHP_EOL; } ``` -------------------------------- ### Create project directory Source: https://www.mongodb.com/docs/drivers/php-frameworks/llphant Commands to initialize the project directory structure. ```bash mkdir llphant-quickstart cd llphant-quickstart ``` -------------------------------- ### Initialize Drupal Project Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Creates a new Drupal project directory using Composer. ```bash composer create-project drupal/recommended-project:11.1.5 drupal-quickstart cd drupal-quickstart ``` -------------------------------- ### Create Laravel Project Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/application-tutorial Initialize a new Laravel project and enter the directory. ```bash composer create-project laravel/laravel LaravelMongodbProject cd LaravelMongodbProject ``` -------------------------------- ### Autocomplete Query Output Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/atlas-search Example JSON output from an autocomplete query. ```json [ "Dreaming of Jakarta", "Jakob the Liar", "Emily Calling Jake" ] ``` -------------------------------- ### Retrieve All Documents Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query Fetches all documents from a collection using the get() or all() methods. ```php SampleModel::get(); // Or, use the all() method. SampleModel::all(); ``` -------------------------------- ### Create Drupal Settings File Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Initialize the settings.php file and set appropriate write permissions. ```bash cd web/sites/default cp default.settings.php settings.php chmod 777 settings.php cd ../../.. ``` -------------------------------- ### Initialize Symfony Project Source: https://www.mongodb.com/docs/drivers/php-frameworks/symfony Creates a new skeleton Symfony project named restaurants. ```bash composer create-project symfony/skeleton restaurants ``` -------------------------------- ### Install Laravel MongoDB Dependency Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Adds the mongodb/laravel-mongodb package to the project dependencies. ```bash composer require mongodb/laravel-mongodb:^5.8 ``` -------------------------------- ### Install MongoDB Module Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Adds the Drupal MongoDB module dependency to the project. ```bash composer require drupal/mongodb:^3.1 ``` -------------------------------- ### Sample Application Output Source: https://www.mongodb.com/docs/drivers/php-frameworks/llphant Expected console output after successfully running the semantic search application. ```text Adding sample documents... Added: Le Bernardin Added: Au Za'atar Added: Bacaro Added: Levant Added: Hangawi Performing semantic search... Query: High-end restaurant with unique options and a romantic atmosphere Search Results: 1. Au Za'atar Description: Polished eatery offering shawarma, mezze, and Lebanese dishes, plus outdoor dining. Features authent... 2. Bacaro Description: Candlelit basement eatery serving pastas & Venetian small plates alongside Italian wines. Intimate I... 3. Hangawi Description: Upscale menu of creative, gourmet Korean fare in a tranquil space where shoes come off at the door. ... ``` -------------------------------- ### Configure Environment Variables Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Define the database connection and URI in the .env file. ```bash DB_CONNECTION=mongodb DB_URI="" ``` ```bash DB_URI="mongodb+srv://myUser:myPass123@mongo0.example.com/" ``` -------------------------------- ### Navigate to Application Directory Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Changes the current working directory to the newly created application folder. ```bash cd my-app ``` -------------------------------- ### Secure Drupal Settings Files Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Restrict write access to settings files after the installation is complete. ```bash chmod 555 web/sites/default chmod 444 web/sites/default/settings.php ``` -------------------------------- ### Configure Connection Options in config/database.php Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/connection-options Use the 'options' array to define connection settings such as application name and compression parameters. ```php 'connections' => [ 'mongodb' => [ 'dsn' => 'mongodb+srv://mongodb0.example.com/', 'driver' => 'mongodb', 'database' => 'sample_mflix', 'options' => [ 'appName' => 'myLaravelApp', 'compressors' => 'zlib', 'zlibCompressionLevel' => 7, ], ], ], ``` -------------------------------- ### Deprecation Notice Example Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/upgrade The notice emitted by the library when using the deprecated 'array' cast type. ```none USER DEPRECATED The "array" cast on attribute "" of model "" stores values as a JSON-encoded string in MongoDB, which is not the native format. Remove the cast to store native BSON arrays. If you must keep JSON string storage, use the "json" cast explicitly. ``` -------------------------------- ### List collections via Artisan command Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/database-collection Execute this command from the project root to display database information and a list of collections. ```bash php artisan db:show ``` -------------------------------- ### Example MongoDB Document Structure Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial The resulting JSON structure after inserting nested data into MongoDB. ```json { "_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" } } ``` -------------------------------- ### Run Database Migrations Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/user-authentication Command to apply database schema changes. ```bash php artisan migrate ``` -------------------------------- ### Replica Set Connection String Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/connect-to-mongodb Configure this connection string in your .env file to connect to a replica set, providing multiple hosts for high availability. ```bash DB_URI="mongodb://myUser:myPass123@host1:27017,host2:27017,host3:27017/?replicaSet=myRS" ``` -------------------------------- ### Configure environment variables Source: https://www.mongodb.com/docs/drivers/php-frameworks/llphant Define API keys and connection strings in the .env file. ```bash VOYAGE_AI_API_KEY= MONGODB_URI= ``` -------------------------------- ### Sample Concert Eloquent Model Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/delete The base model class used for delete operations in this guide. ```php 'datetime']; } ``` -------------------------------- ### Install Doctrine MongoDB ODM Bundle Source: https://www.mongodb.com/docs/drivers/php-frameworks/symfony Adds the Doctrine MongoDB ODM bundle to the Symfony application. ```bash composer require doctrine/mongodb-odm-bundle ``` -------------------------------- ### Instantiate and Save Related Models Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/relationships Demonstrates creating model instances and persisting the relationship between them. ```php $planet = new Planet(); $planet->name = 'Earth'; $planet->diameter_km = 12742; $planet->save(); $orbit = new Orbit(); $orbit->period = 365.26; $orbit->direction = 'counterclockwise'; $planet->orbit()->save($orbit); ``` -------------------------------- ### Create Authentication Controller Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/user-authentication Commands to generate an authentication controller using Artisan. ```php php artisan make:controller ``` ```php php artisan make:controller AuthController ``` -------------------------------- ### Vector Search Query Output Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/vector-search Example JSON output returned from a successful vector search query. ```json [ { "title": "Sunrising", "plot": "A shy teenager discovers confidence and new friendships during a transformative summer camp experience." }, { "title": "Last Semester", "plot": "High school friends navigate love, identity, and unexpected challenges before graduating together." } ] ``` -------------------------------- ### Insert Sample Documents Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/aggregation-builder Populates the User model collection with sample data using the insert method. ```php User::insert([ ['name' => 'Alda Gröndal', 'occupation' => 'engineer', 'birthday' => new UTCDateTime(new DateTimeImmutable('2002-01-01'))], ['name' => 'Francois Soma', 'occupation' => 'engineer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1998-02-02'))], ['name' => 'Janet Doe', 'occupation' => 'designer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1987-03-03'))], ['name' => 'Eliud Nkosana', 'occupation' => 'engineer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1984-04-04'))], ['name' => 'Bran Steafan', 'occupation' => 'engineer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1998-05-05'))], ['name' => 'Ellis Lee', 'occupation' => 'designer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1996-06-06'))], ]); ``` -------------------------------- ### Query Log Output Format Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query/query-logging Example of the JSON output structure returned by the query log methods. ```json { "query": "{ \"find\" : \"movies\", \"filter\" : { \"title\" : \"Carrie\" } }", "bindings": [], "time": 29476 } { "query": "{ \"find\" : \"movies\", \"filter\" : { \"year\" : { \"$lt\" : { \"$numberInt\" : \"2005\" } } } }", "bindings": [], "time": 29861 } { "query": "{ \"find\" : \"movies\", \"filter\" : { \"imdb.rating\" : { \"$gt\" : { \"$numberDouble\" : \"8.5\" } } } }", "bindings": [], "time": 27251 } ``` -------------------------------- ### Select Database and List Collections Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Commands to switch to the drupal database and list all available collections. ```javascript use drupal show collections ``` -------------------------------- ### Node Collection Document Output Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Example JSON document structure returned when querying the node collection. ```text [ { _id: ObjectId('...'), nid: 1, vid: 1, type: 'article', uuid: '...', langcode: 'en', node_all_revisions: [ { ... } ], node_current_revision: [ { ... } ], node_latest_revision: [ { ... title: 'Welcome to My Drupal Site', created: ..., changed: ..., promote: true, sticky: false, default_langcode: true, revision_default: true, revision_translation_affected: true, node_latest_revision__body: [ { bundle: 'article', deleted: false, langcode: 'en', entity_id: 1, revision_id: 1, delta: 0, body_value: '

This is my first article on Drupal with MongoDB!
All content is stored as JSON documents in MongoDB.

', body_summary: '', body_format: 'basic_html' } ], node_latest_revision__comment: [ { bundle: 'article', deleted: false, langcode: 'en', comment_status: 2, entity_id: 1, revision_id: 1, delta: 0 } ] } ] } ] ``` -------------------------------- ### Enable TLS via Connection String Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/tls Configure TLS by appending the tls=true parameter to the DSN string in the database configuration. ```php 'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => 'mongodb://:/?tls=true', 'database' => 'myDB', ] ] ``` -------------------------------- ### Retrieve Multiple Documents Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query Use the get() method to retrieve all documents that match the specified query filter. ```php SampleModel::where('', '') ->get(); ``` -------------------------------- ### Fix Deprecated Boolean Cast Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Replace the deprecated (boolean) cast with (bool) in DocParser.php to resolve installation errors. ```php $this->ignoreNotImportedAnnotations = (boolean) $bool; ``` ```php $this->ignoreNotImportedAnnotations = (bool) $bool; ``` -------------------------------- ### Configure Drupal File Permissions Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Create the public files directory and set permissions for Drupal to write content. ```bash mkdir -p web/sites/default/files chmod -R 777 web/sites/default/files ``` -------------------------------- ### Error handling for update() Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/modify Example of the error returned when the retrieval part of an update chain fails to match any documents. ```none Error: Call to a member function update() on null ``` -------------------------------- ### Updating Documents with updateOne Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial Demonstrates updating a document using the native updateOne method. ```php 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()]; }); ``` -------------------------------- ### Define Search Queries Source: https://www.mongodb.com/docs/drivers/php-frameworks/llphant Examples of search query variables to modify in index.php for testing different semantic results. ```bash # Sample search queries $searchQuery = "Casual place for Middle Eastern food"; $searchQuery = "Modern Italian restaurant"; $searchQuery = "Affordable restaurants serving Asian cuisine"; ``` -------------------------------- ### Set Environment Variables Source: https://www.mongodb.com/docs/drivers/php-frameworks/symfony Define MongoDB connection string and database name in the .env file. ```none ... MONGODB_URL= MONGODB_DB=sample_restaurants ``` -------------------------------- ### Create Sparse and TTL Indexes Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/schema-builder Use the sparse and expire methods on the Blueprint instance to define index properties. ```php Schema::create('planets', function (Blueprint $collection) { $collection->sparse('rings'); $collection->expire('last_visible_dt', 86400); }); ``` -------------------------------- ### Retrieve All Documents Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query/retrieve Fetch all documents in a collection by calling get() on the Eloquent model. The all() method serves as an alias for this operation. ```php $movies = Movie::get(); ``` -------------------------------- ### Instantiate and Save Related Models Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/relationships Demonstrates creating parent and child records and associating them using the relationship method. ```php $planet = new Planet(); $planet->name = 'Jupiter'; $planet->diameter_km = 142984; $planet->save(); $moon1 = new Moon(); $moon1->name = 'Ganymede'; $moon1->orbital_period = 7.15; $moon2 = new Moon(); $moon2->name = 'Europa'; $moon2->orbital_period = 3.55; $planet->moons()->save($moon1); $planet->moons()->save($moon2); ``` -------------------------------- ### Create Laravel Application Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Generates a new Laravel project named my-app. ```bash laravel new my-app ``` -------------------------------- ### Increase ulimit for MongoDB Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Prevents system resource limitations by increasing the open file limit before starting the replica set. ```bash ulimit -n 64000 ``` -------------------------------- ### Specify Index Options Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/schema-builder Pass additional configuration like collation settings to index creation methods via the options parameter. ```php Schema::create('passengers', function (Blueprint $collection) { $collection->index( 'last_name', name: 'passengers_collation_idx', options: [ 'collation' => [ 'locale' => 'de@collation=phonebook', 'numericOrdering' => true ], ], ); }); ``` ```json [ { v: 2, key: { _id: 1 }, name: '_id_' }, { v: 2, key: { last_name: 1 }, name: 'passengers_collation_idx', collation: { locale: 'de@collation=phonebook', caseLevel: false, caseFirst: 'off', strength: 3, numericOrdering: true, alternate: 'non-ignorable', maxVariable: 'punct', normalization: false, backwards: false, version: '57.1' } } ] ``` -------------------------------- ### Update Environment Variables Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/application-tutorial Configure the connection string and default database driver in the .env file. ```json MONGODB_URI=mongodb+srv://YOUR_MONGODB_CONNECTION_STRING DB_CONNECTION=mongodb // Other DB_ values here ... SESSION_DRIVER=mongodb ``` -------------------------------- ### Create MongoDB Search Index Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/scout Run the artisan command to create the search collection and index. ```bash php artisan scout:index 'App\Models\Movie' ``` -------------------------------- ### Find Multiple Documents with Eloquent Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query/retrieve Retrieves a collection of documents matching a runtime threshold using where, orderBy, and get methods. ```php $movies = Movie::where('runtime', '>', 900) ->orderBy('id') ->get(); ``` -------------------------------- ### Migrating Model Casts Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/upgrade Examples showing how to update Eloquent model casts by removing the deprecated 'array' type or replacing it with 'json'. ```php // Before (deprecated in v5.8) protected $casts = [ 'options' => 'array', ]; // After: remove the cast to use native BSON storage protected $casts = [ // other casts... ]; ``` ```php protected $casts = [ 'options' => 'json', ]; ``` -------------------------------- ### Retrieve Distinct Field Values with Eloquent Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query/retrieve Retrieves unique values for a specific field from documents matching a director filter using where, select, distinct, and get methods. ```php $ratings = Movie::where('directors', 'Sofia Coppola') ->select('imdb.rating') ->distinct() ->get(); echo $ratings; ``` -------------------------------- ### Group Aggregation Stage Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/aggregation-builder Use the group method to modify data structure by grouping by common field values. This example uses the Expression builder to define the group key. ```php $pipeline = User::aggregate() ->group(_id: Expression::fieldPath('occupation')); $result = $pipeline->get(); ``` -------------------------------- ### Accessing Collections via Schema and DB Facades Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/upgrade Illustrates the migration from collection-specific methods to table-based methods for Schema and DB operations. ```php use Illuminate\\Support\\Facades\\Schema; use Illuminate\\Support\\Facades\\DB; use MongoDB\\Laravel\\Schema\\Blueprint; // older versions Schema::collection('app_user', function (Blueprint $collection) { ... }); DB::collection('app_user')->find($id); // v5.0 Schema::table('app_user', function (Blueprint $table) { ... }); DB::table('app_user')->find($id); ``` -------------------------------- ### Configure TLS with Certificates Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/tls Use the options array to specify TLS settings and paths to required certificate files for secure connections. ```php 'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => '', 'database' => 'myDB', 'options' => [ 'tls' => true, 'tlsCAFile' => '', 'tlsCertificateKeyFile' => '', 'tlsCertificateKeyFilePassword' => '', ] ] ] ``` -------------------------------- ### Configure Connection Options via DSN Query String Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/connection-options Append connection options directly to the DSN string using standard query parameter syntax. ```php 'dsn' => 'mongodb+srv://mongodb0.example.com/?appName=myLaravelApp&compressors=zlib', ``` -------------------------------- ### Instantiate Models and Attach Relationships Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/relationships Creates model instances and establishes the many to many relationship using the attach method. ```php $planetEarth = new Planet(); $planetEarth->name = 'Earth'; $planetEarth->save(); $planetMars = new Planet(); $planetMars->name = 'Mars'; $planetMars->save(); $planetJupiter = new Planet(); $planetJupiter->name = 'Jupiter'; $planetJupiter->save(); $explorerTanya = new SpaceExplorer(); $explorerTanya->name = 'Tanya Kirbuk'; $explorerTanya->save(); $explorerMark = new SpaceExplorer(); $explorerMark->name = 'Mark Watney'; $explorerMark->save(); $explorerJeanluc = new SpaceExplorer(); $explorerJeanluc->name = 'Jean-Luc Picard'; $explorerJeanluc->save(); $explorerTanya->planetsVisited()->attach($planetEarth); $explorerTanya->planetsVisited()->attach($planetJupiter); $explorerMark->planetsVisited()->attach($planetEarth); $explorerMark->planetsVisited()->attach($planetMars); $explorerJeanluc->planetsVisited()->attach($planetEarth); $explorerJeanluc->planetsVisited()->attach($planetMars); $explorerJeanluc->planetsVisited()->attach($planetJupiter); ``` -------------------------------- ### Create Sparse, TTL, and Unique Indexes via Options Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/schema-builder Pass an options array to the index method to define multiple index properties simultaneously. ```php Schema::create('planet_systems', function (Blueprint $collection) { $collection->index('last_visible_dt', options: ['sparse' => true, 'expireAfterSeconds' => 3600, 'unique' => true]); }); ``` -------------------------------- ### Configure GridFS with Factory Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/filesystems Use a factory or service name to provide a custom MongoDB\GridFS\Bucket instance. ```php use Illuminate\Foundation\Application; use MongoDB\GridFS\Bucket; 'disks' => [ 'gridfs' => [ 'driver' => 'gridfs', 'bucket' => static function (Application $app): Bucket { return $app['db']->connection('mongodb') ->getDatabase() ->selectGridFSBucket([ 'bucketName' => 'avatars', 'chunkSizeBytes' => 261120, ]); }, ], ], ``` -------------------------------- ### Generate Task Model and Controller Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/application-tutorial Artisan command to scaffold the Task model and resource controller. ```bash php artisan make:model Task --resource --controller ``` -------------------------------- ### Create Model and Controller Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started Generates a new Eloquent model and resource controller using Artisan. ```bash php artisan make:model Movie -cr ``` -------------------------------- ### Executing Aggregation Pipelines Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial Demonstrates defining and executing an aggregation pipeline to compute average ratings by genre. ```php 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() ]; }); ``` -------------------------------- ### Use Cache Facade Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/integrations/cache Access the cache store using the Illuminate facade. ```php use Illuminate\Support\Facades\Cache; Cache::get('foo', 5); ``` -------------------------------- ### Create and attach embedded models Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/relationships Shows how to instantiate models and use the attach method to add them to an embedded relationship. ```php $spaceship = new SpaceShip(); $spaceship->name = 'The Millenium Falcon'; $spaceship->save(); $cargoSpice = new Cargo(); $cargoSpice->name = 'spice'; $cargoSpice->weight = 50; $cargoHyperdrive = new Cargo(); $cargoHyperdrive->name = 'hyperdrive'; $cargoHyperdrive->weight = 25; $spaceship->cargo()->attach($cargoSpice); $spaceship->cargo()->attach($cargoHyperdrive); ``` -------------------------------- ### List Collection Fields via Shell Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/database-collection Use the artisan command to display collection fields and their data types from the project root. ```bash php artisan db:table ``` -------------------------------- ### Connect to MongoDB Replica Set Source: https://www.mongodb.com/docs/drivers/php-frameworks/drupal Establishes a connection to the local three-node replica set using the MongoDB Shell. ```javascript mongosh "mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0" ``` -------------------------------- ### Configure Multiple Database Connections Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/database-collection Define multiple database connections in config/database.php to access different databases. ```php 'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => 'mongodb://localhost:27017/', 'database' => 'animals', ], 'mongodb_alt' => [ 'driver' => 'mongodb', 'dsn' => 'mongodb://localhost:27017/', 'database' => 'plants', ] ], ... ``` -------------------------------- ### Insert a document using the save() method Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/insert Instantiate a model, assign values to its properties, and persist it to the database using the save() method. ```php $concert = new Concert(); $concert->performer = 'Mitsuko Uchida'; $concert->venue = 'Carnegie Hall'; $concert->genres = ['classical']; $concert->ticketsSold = 2121; $concert->performanceDate = Carbon::create(2024, 4, 1, 20, 0, 0, 'EST'); $concert->save(); ``` -------------------------------- ### Deleting Documents with deleteOne Source: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial Demonstrates deleting a document using the native deleteOne method. ```php 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() ]; }); ```