PHPackages                             toporia/mongodb - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. toporia/mongodb

ActiveLibrary[Database &amp; ORM](/categories/database)

toporia/mongodb
===============

MongoDB ODM for Toporia Framework - Document-oriented database support with embedded documents, references, and aggregation pipelines

00PHP

Since Dec 16Pushed 5mo agoCompare

[ Source](https://github.com/Minhphung7820/toporia-mongodb)[ Packagist](https://packagist.org/packages/toporia/mongodb)[ RSS](/packages/toporia-mongodb/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Toporia MongoDB
===============

[](#toporia-mongodb)

MongoDB ODM (Object Document Mapper) for Toporia Framework with embedded documents, references, and aggregation pipelines.

Features
--------

[](#features)

- **Document-Oriented Models** - ODM similar to ORM for MongoDB collections
- **Embedded Documents** - Support for nested documents (EmbedsOne, EmbedsMany)
- **References** - Document references (ReferencesOne, ReferencesMany)
- **Aggregation Pipelines** - Fluent interface for MongoDB aggregation
- **Query Builder** - MongoDB-specific query builder with all operators
- **Schema Management** - Collection and index management

Requirements
------------

[](#requirements)

- **PHP**: &gt;= 8.1
- **Toporia Framework**: ^1.0
- **mongodb/mongodb**: ^1.17
- **ext-mongodb**: MongoDB PHP extension

Installation
------------

[](#installation)

```
composer require toporia/mongodb
```

Auto-Discovery
--------------

[](#auto-discovery)

This package uses Toporia's **Package Auto-Discovery** system. After installation:

- **Service Provider** is automatically registered - no manual registration required
- **Configuration** is automatically discovered from `extra.toporia.config` in composer.json

To rebuild the package manifest manually:

```
php console package:discover
```

Setup
-----

[](#setup)

### 1. Install MongoDB PHP Extension

[](#1-install-mongodb-php-extension)

```
# Ubuntu/Debian
sudo pecl install mongodb
echo "extension=mongodb.so" | sudo tee /etc/php/8.1/cli/conf.d/mongodb.ini

# macOS with Homebrew
pecl install mongodb
```

### 2. Publish Config (optional)

[](#2-publish-config-optional)

```
php console vendor:publish --provider="Toporia\MongoDB\MongoDBServiceProvider"
# Or with tag
php console vendor:publish --tag=mongodb-config
```

### 3. Configure Environment

[](#3-configure-environment)

Add to your `.env` file:

```
MONGO_HOST=localhost
MONGO_PORT=27017
MONGO_DATABASE=your_database
MONGO_USERNAME=
MONGO_PASSWORD=
MONGO_AUTH_DATABASE=admin
```

Configuration
-------------

[](#configuration)

```
// config/mongodb.php
return [
    'default' => 'mongodb',

    'connections' => [
        'mongodb' => [
            'driver' => 'mongodb',
            'host' => env('MONGO_HOST', 'localhost'),
            'port' => env('MONGO_PORT', 27017),
            'database' => env('MONGO_DATABASE', 'toporia'),
            'username' => env('MONGO_USERNAME', ''),
            'password' => env('MONGO_PASSWORD', ''),
            'options' => [
                'authSource' => env('MONGO_AUTH_DATABASE', 'admin'),
            ],
        ],
    ],
];
```

Usage
-----

[](#usage)

### Basic Model

[](#basic-model)

```
use Toporia\MongoDB\ORM\MongoDBModel;

class Post extends MongoDBModel
{
    protected static string $collection = 'posts';

    protected static array $fillable = ['title', 'content', 'author_id'];

    protected static array $casts = [
        'created_at' => 'datetime',
        'views' => 'integer',
    ];
}

// Create
$post = Post::create([
    'title' => 'Hello MongoDB',
    'content' => 'First post',
]);

// Find
$post = Post::find($id);

// Query
$posts = Post::where('author_id', $userId)->get();
```

### Embedded Documents

[](#embedded-documents)

```
class User extends MongoDBModel
{
    protected static string $collection = 'users';

    public function address()
    {
        return $this->embedsOne(Address::class);
    }

    public function phones()
    {
        return $this->embedsMany(Phone::class);
    }
}

// Access embedded
$user = User::find($id);
echo $user->address->city;

foreach ($user->phones as $phone) {
    echo $phone->number;
}
```

### References

[](#references)

```
class Author extends MongoDBModel
{
    public function posts()
    {
        return $this->referencesMany(Post::class, 'author_id');
    }
}

class Post extends MongoDBModel
{
    public function author()
    {
        return $this->belongsToReference(Author::class, 'author_id');
    }
}

// Access references
$author = Author::find($id);
$posts = $author->posts; // Lazy loaded
```

### Aggregation Pipeline

[](#aggregation-pipeline)

```
$results = Post::aggregate()
    ->match(['status' => 'published'])
    ->group([
        '_id' => '$author_id',
        'total_posts' => ['$sum' => 1],
        'total_views' => ['$sum' => '$views'],
    ])
    ->sort(['total_posts' => -1])
    ->limit(10)
    ->get();
```

### Query Builder

[](#query-builder)

```
// MongoDB-specific operators
$posts = Post::where('views', '>', 100)
    ->whereIn('tags', ['php', 'mongodb'])
    ->whereExists('featured_image')
    ->orderBy('created_at', 'desc')
    ->limit(10)
    ->get();

// Text search
$results = Post::whereText('mongodb tutorial')->get();

// Geo queries
$nearby = Location::whereNear('coordinates', [
    'latitude' => 40.7128,
    'longitude' => -74.0060,
], 5000)->get(); // Within 5km
```

Helper Functions
----------------

[](#helper-functions)

```
mongodb();                          // Get MongoDB manager
mongodb_connection('mongodb');      // Get specific connection
mongodb_collection('posts');        // Get collection directly
```

License
-------

[](#license)

MIT

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance50

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/1cc240e87c451f2dd614b87bb0d07039e4a20d8b391221c651172cf341e0b6cd?d=identicon)[Minhphung7820](/maintainers/Minhphung7820)

---

Top Contributors

[![Minhphung7820](https://avatars.githubusercontent.com/u/110077842?v=4)](https://github.com/Minhphung7820 "Minhphung7820 (5 commits)")

### Embed Badge

![Health badge](/badges/toporia-mongodb/health.svg)

```
[![Health](https://phpackages.com/badges/toporia-mongodb/health.svg)](https://phpackages.com/packages/toporia-mongodb)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
