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 --database=mongodb, inspect queries with ->dump().

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

Reference fileLoad when
references/eloquent-models.mdThe user is defining a new model, changing its base class, or mapping _id / ObjectId fields
references/query-builder.mdThe user is writing a query and hits a missing Eloquent helper (toSql, distinct, grouping, random ordering, raw SQL builders) or needs relation aggregates
references/relationships.mdThe user is defining a relationship between models, especially embedded, hybrid, or cross-database (MongoDB ↔ SQL) relations
references/connection.mdThe user is configuring config/database.php, setting up multiple connections, or accessing the underlying MongoDB client
references/schema.mdThe user is writing a migration or creating an index (regular, unique, TTL, geospatial, Atlas Search, Vector Search)
references/queues.mdThe user is configuring the MongoDB queue driver or dispatching jobs onto it
references/transactions.mdThe user needs to write multiple documents atomically or is asking about beginTransaction, replica set requirements, or transactional testing traits
references/cache-sessions.mdThe user is configuring MongoDB as a cache store or session driver
references/search-engine.mdThe user is implementing full-text search on a MongoDB collection or is deciding whether to use Laravel Scout
references/vector-search.mdThe user is implementing semantic search, storing embeddings, using autoEmbed, or combining full-text and vector search
references/queryable-encryption.mdThe user is encrypting sensitive fields or configuring automatic encryption (autoEncryption)
references/installation.mdThe user is setting up ext-mongodb, installing the package, or configuring the connection for the first time
references/support.mdThe user has hit a suspected bug and needs to route the issue to the correct MongoDB repository

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 (see references/queryable-encryption.md).

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
Indexes / migrationphp artisan migrate --database=mongodbMigrations run; indexes created
Query inspectionModel::query()->where(...)->dump()Prints MongoDB filter array (no SQL)

Skills เพิ่มเติมจาก mongodb

atlas-stream-processing
mongodb
จัดการเวิร์กโฟลว์ MongoDB Atlas Stream Processing (ASP) ดูแลการจัดเตรียมเวิร์กสเปซ การเชื่อมต่อแหล่งข้อมูล/ซิงก์ การดำเนินการวงจรชีวิตของโปรเซสเซอร์…
mongodb-atlas-stream-processing
mongodb
จัดการเวิร์กโฟลว์ MongoDB Atlas Stream Processing (ASP) ดูแลการจัดเตรียมเวิร์กสเปซ การเชื่อมต่อแหล่งข้อมูล/ปลายทาง การดำเนินการวงจรชีวิตของโปรเซสเซอร์,…
mongodb-connection
mongodb
ปรับแต่งการกำหนดค่าการเชื่อมต่อไคลเอนต์ MongoDB (พูล, ไทม์เอาต์, รูปแบบ) สำหรับภาษาไดรเวอร์ที่รองรับใด ๆ ใช้ทักษะนี้เมื่อทำงาน/อัปเดต/ตรวจสอบ…
mongodb-mcp-setup
mongodb
แนะนำผู้ใช้ในการกำหนดค่าตัวเลือกหลักของ MongoDB MCP server ใช้สกิลนี้เมื่อผู้ใช้ติดตั้ง MongoDB MCP server แล้วแต่ยังไม่ได้กำหนดค่า…
mongodb-natural-language-querying
mongodb
สร้างคิวรี MongoDB แบบอ่านอย่างเดียว (find) หรือ aggregation pipelines โดยใช้ภาษาธรรมชาติ พร้อมบริบทของ schema คอลเลกชันและเอกสารตัวอย่าง ใช้สกิลนี้…
mongodb-query-optimizer
mongodb
ช่วยเหลือเกี่ยวกับการปรับแต่งคิวรี MongoDB และการสร้างดัชนี ใช้เฉพาะเมื่อผู้ใช้ขอการปรับแต่งหรือประสิทธิภาพ: "ฉันจะปรับแต่งคิวรีนี้อย่างไร?", "ฉันจะ...
mongodb-schema-design
mongodb
รูปแบบและแนวทางปฏิบัติที่ไม่ควรทำในการออกแบบ schema ของ MongoDB ใช้เมื่อออกแบบโมเดลข้อมูล ตรวจสอบ schema ย้ายข้อมูลจาก SQL หรือแก้ไขปัญหาด้านประสิทธิภาพ...
mongodb-search-and-ai
mongodb
แนะนำผู้ใช้ MongoDB ในการนำไปใช้และเพิ่มประสิทธิภาพโซลูชัน Atlas Search (full-text), Vector Search (semantic) และ Hybrid Search ใช้ทักษะนี้เมื่อ...