laravel-mongodb

작성자: mongodb

mongodb/laravel-mongodb 패키지의 구현 전문가입니다. "Laravel MongoDB", "mongodb/laravel-mongodb", "Eloquent MongoDB", "MongoDB…"에서 트리거됩니다.

npx skills add https://github.com/mongodb/laravel-mongodb --skill laravel-mongodb

Laravel MongoDB

Implementation skill for mongodb/laravel-mongodb. Exists to prevent the common mistakes: auto-increment IDs, toSql(), SQL JOIN, distinct()->get() expecting scalar arrays, and belongsTo() over native ObjectId FKs.

Core Workflow

  1. Identify layer: model, query builder, relationship, schema/index, queue/cache/session, search, or transaction.
  2. Confirm model extends MongoDB\Laravel\Eloquent\Model (or uses DocumentModel trait).
  3. Map every FK and _id: ObjectId in DB, string in Eloquent — cast accordingly.
  4. Replace unsupported helpers (toSql, groupByRaw, whereFulltext, union, inRandomOrder, whereColumn) with MongoDB alternatives.
  5. Validate: php artisan migrate, Pest tests, phpcs/phpstan.

Related MongoDB tooling

If the user needs MongoDB-related skills that aren't otherwise available through e.g. Boost or the skills directory, such as:

  • Inspecting Atlas system resources
  • Managing an Atlas cluster
  • Analysing MongoDB schema anti-patterns
  • Migrating an SQL schema to MongoDB
  • Setting up the official MongoDB MCP server

Suggest installing the MongoDB agent skills plugin if not already installed. Instructions for installing it are in the MongoDB agent skills plugin README.

Reference Guide

TopicReference fileLoad When
Models, casts, _id mappingreferences/eloquent-models.mdDefining or modifying a model
Query builder gotchas, aggregationreferences/query-builder.mdWriting queries, relation aggregates, distinct, grouping
Embedded, hybrid, cross-database relationsreferences/relationships.mdbelongsTo, hasMany, embedsMany, hasManyIn
Connection setupreferences/connection.mdconfig/database.php, multiple connections
Indexes, migrationsreferences/schema.mdCreating indexes, migrations, collections
Queue driverreferences/queues.mdDispatching jobs, queue config
Transactionsreferences/transactions.mdMulti-document atomic writes
Cache & sessionsreferences/cache-sessions.mdConfiguring cache / session stores
Atlas Search / Scoutreferences/search-engine.mdFull-text search, Scout integration
Vector search, auto-embeddingreferences/vector-search.mdSemantic search, embedding pipelines, hybrid search
Installationreferences/installation.mdSetting up ext-mongodb and the package
Support & issue reportingreferences/support.mdReporting bugs, finding the right repo

Constraints

MUST DO

  • Extend MongoDB\Laravel\Eloquent\Model (or apply DocumentModel trait to base classes you cannot change).
  • Cast _id to string in every API resource: 'id' => (string) $this->_id.
  • Cast FK fields to string via $casts on the child model when FK values may come from outside model attributes (imports, raw ObjectIds) — prevents BSON type mismatches on direct where('author_id', $id) queries.
  • Eager-load with ::with() — MongoDB does no server-side joins for Eloquent relations.
  • Use aggregation pipeline for grouping, counting per group, $lookup, and $sample.
  • Relation aggregates (withCount(), withExists(), withSum(), withAvg(), withMin(), withMax()) are supported. Use a $lookup pipeline when the aggregated value must be filtered, sorted or paginated on.
  • Create indexes in migrations: Schema::connection('mongodb')->create('posts', fn (Blueprint $c) => $c->index('user_id')).
  • Use DB::connection('mongodb')->transaction(...) only on replica set / sharded cluster.

MUST NOT DO

  • orderBy() on a withCount() / withAggregate() alias — the value is computed after the documents are read, so it throws. Use $lookup + $size aggregation, or sort the resulting collection.
  • toSql() / toRawSql() — no SQL. Use ->dump() / ->dd().
  • distinct('field')->get() expecting scalars — returns a Collection. Use ->distinct()->pluck('field').
  • groupByRaw(), orderByRaw(), havingRaw(), whereFulltext(), union(), whereColumn() — use aggregation.
  • inRandomOrder() — use Model::raw(fn($c) => $c->aggregate([['$sample' => ['size' => N]]])).
  • Auto-increment IDs — primary keys are ObjectIds.
  • protected $collection — removed. Use protected $table instead.
  • $keyType = 'string' on a SQL model in a cross-database relationship — only needed on MongoDB models. The HybridRelations trait handles the comparison on the SQL side.
  • Unencrypted PII — use Laravel encrypted casts or Queryable Encryption.

Code Templates

1. Eloquent model

<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

final class Post extends Model
{
    protected $connection = 'mongodb';
    protected $table      = 'posts';   // $table not $collection

    protected $fillable = ['title', 'body', 'author_id', 'published_at'];

    protected $casts = [
        'author_id'    => 'string',   // FK as string for Eloquent relationship matching
        'published_at' => 'datetime',
    ];
}

2. Relationship with ObjectId/string casting

<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;
use MongoDB\Laravel\Relations\BelongsTo;
use MongoDB\Laravel\Relations\EmbedsMany;

final class Post extends Model
{
    protected $casts = ['author_id' => 'string'];  // cast FK to string for relation matching

    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    public function comments(): EmbedsMany
    {
        return $this->embedsMany(Comment::class);
    }
}

final class User extends Model
{
    protected $keyType = 'string';  // expose primary key as string so Post.author_id matches
}

3. Queue job

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

final class IndexPostJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public string $postId) {}

    public function handle(): void {}
}

IndexPostJob::dispatch((string) $post->_id)->onConnection('mongodb');

4. Feature test (Pest)

<?php

use App\Models\Post;

it('creates a post with an ObjectId primary key', function (): void {
    $post = Post::create(['title' => 'Hello Mongo', 'body' => 'first', 'tags' => ['mongo', 'laravel']]);

    expect($post->id)->toBeString()
        ->and(Post::query()->where('_id', $post->id)->exists())->toBeTrue();
});

Validation Checkpoints

StageCommandExpected Result
Stylevendor/bin/phpcbf && vendor/bin/phpcsNo violations
Static analysisvendor/bin/phpstan analyseLevel 8 clean
Indexes / migrationphp artisan migrate --database=mongodbMigrations run; indexes created
Testsvendor/bin/pestAll green
Query inspectionModel::query()->where(...)->dump()Prints MongoDB filter array (no SQL)

mongodb의 다른 스킬

atlas-stream-processing
mongodb
MongoDB Atlas Stream Processing(ASP) 워크플로우를 관리합니다. 워크스페이스 프로비저닝, 데이터 소스/싱크 연결, 프로세서 수명 주기 작업을 처리합니다.
official
mongodb-atlas-stream-processing
mongodb
MongoDB Atlas Stream Processing(ASP) 워크플로우를 관리합니다. 워크스페이스 프로비저닝, 데이터 소스/싱크 연결, 프로세서 수명 주기 작업을 처리합니다.…
official
mongodb-connection
mongodb
지원되는 모든 드라이버 언어에 대해 MongoDB 클라이언트 연결 구성(연결 풀, 시간 초과, 패턴)을 최적화합니다. 작업/업데이트/검토 시 이 스킬을 사용하세요…
official
mongodb-mcp-setup
mongodb
사용자가 MongoDB MCP 서버 옵션을 구성하는 과정을 안내합니다. MongoDB MCP 서버는 설치했지만 아직 구성하지 않은 경우 이 스킬을 사용하세요.
official
mongodb-natural-language-querying
mongodb
자연어를 사용하여 컬렉션 스키마 컨텍스트와 샘플 문서를 바탕으로 읽기 전용 MongoDB 쿼리(find) 또는 집계 파이프라인을 생성합니다. 이 스킬을 사용하여…
official
mongodb-query-optimizer
mongodb
MongoDB 쿼리 최적화 및 인덱싱에 도움을 줍니다. 사용자가 "이 쿼리를 어떻게 최적화하나요?", "어떻게…"와 같이 최적화 또는 성능에 대해 질문할 때만 사용하세요.
official
mongodb-schema-design
mongodb
MongoDB 스키마 설계 패턴 및 안티패턴. 데이터 모델 설계, 스키마 검토, SQL에서 마이그레이션, 또는 성능 문제 해결 시 사용하세요…
official
mongodb-search-and-ai
mongodb
MongoDB 사용자가 Atlas Search(전체 텍스트), Vector Search(의미론적), Hybrid Search 솔루션을 구현하고 최적화하는 방법을 안내합니다. 이 스킬은 다음 상황에서 사용하세요…
official