PHPackages                             mosesanu/laravel-mongodb-query-monitor - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. mosesanu/laravel-mongodb-query-monitor

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

mosesanu/laravel-mongodb-query-monitor
======================================

MongoDB query performance monitoring for Laravel

v1.0.0(3mo ago)291[3 PRs](https://github.com/alloyking1/laravel-mongodb-query-monitor/pulls)MITPHPPHP ^8.2

Since Mar 30Pushed 1mo agoCompare

[ Source](https://github.com/alloyking1/laravel-mongodb-query-monitor)[ Packagist](https://packagist.org/packages/mosesanu/laravel-mongodb-query-monitor)[ RSS](/packages/mosesanu-laravel-mongodb-query-monitor/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependenciesVersions (2)Used By (0)

Laravel MongoDB Query Monitor
=============================

[](#laravel-mongodb-query-monitor)

`laravel-mongodb-query-monitor` helps you inspect MongoDB performance in Laravel by recording:

- MongoDB operation name (`find`, `aggregate`, `insert`, etc.)
- Target collection
- Query duration in milliseconds
- Request duration in milliseconds
- Whether a query is considered slow
- Route path that triggered the query

The package writes logs to a MongoDB collection named `performance_logs`.

How It Works
------------

[](#how-it-works)

The package has two moving parts:

1. A MongoDB command subscriber listens to MongoDB driver events and measures query duration.
2. A Laravel middleware persists all collected query metrics at the end of each HTTP request.

If middleware is not applied, queries may be measured but they will not be saved.

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

[](#requirements)

- PHP `^8.2`
- Laravel application
- A working MongoDB connection configured in Laravel as `mongodb`
- A Laravel MongoDB driver that supports:
    - `DB::connection('mongodb')->getMongoDB()`

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

[](#installation)

Install via Composer:

```
composer require mosesanu/laravel-mongodb-query-monitor
```

Laravel package discovery will automatically register the service provider.

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

[](#configuration)

If you want to change configuration you can publish package's configuration file using the vendor:publish command:

```
php artisan vendor:publish --provider="MosesAnu\MongoQueryMonitor\MongoQueryMonitorServiceProvider"
```

If you are going to record only slow queries you must update your `config/query-monitor.php` file.

```
'record_only_slow_queries' => true,
```

Usage
-----

[](#usage)

### 1. Ensure MongoDB Connection Exists

[](#1-ensure-mongodb-connection-exists)

Your Laravel app must have a database connection named `mongodb`.

Example (`config/database.php`):

```
'connections' => [
	// ...

	'mongodb' => [
		'driver' => 'mongodb',
		'dsn' => env('MONGODB_URI'),
		'database' => env('MONGODB_DATABASE', 'app'),
	],
],
```

### 2. Register the Middleware

[](#2-register-the-middleware)

Apply `PerformanceMiddleware` where you want monitoring to run.

Option A: Global middleware (all web requests)

```
// app/Http/Kernel.php

protected $middleware = [
	// ...
	\MosesAnu\MongoQueryMonitor\Middleware\PerformanceMiddleware::class,
];
```

Option B: Route middleware (selected routes only)

```
// app/Http/Kernel.php

protected $routeMiddleware = [
	// ...
	'mongo.monitor' => \MosesAnu\MongoQueryMonitor\Middleware\PerformanceMiddleware::class,
];
```

```
// routes/web.php or routes/api.php

Route::middleware(['mongo.monitor'])->group(function () {
	Route::get('/reports', [ReportController::class, 'index']);
});
```

### 3. Trigger Queries

[](#3-trigger-queries)

Hit routes that execute MongoDB operations. At response completion, logs are written to:

- Connection: `mongodb`
- Collection: `performance_logs`

Logged Document Shape
---------------------

[](#logged-document-shape)

Each captured query is stored as one MongoDB document:

```
{
  "route": "api/reports",
  "collection": "reports",
  "operation": "find",
  "duration_ms": 14.23,
  "request_duration": 87.41,
  "is_slow": false,
  "created_at": "UTCDateTime"
}
```

Slow Query Threshold
--------------------

[](#slow-query-threshold)

Queries are flagged as slow when duration is greater than `200ms`.

In the current version, this threshold is hard-coded in `QueryMonitorService`.

Quick Verification
------------------

[](#quick-verification)

1. Enable middleware.
2. Call a route that runs MongoDB queries.
3. Inspect `performance_logs` in MongoDB.
4. Confirm documents include `route`, `collection`, `operation`, and duration fields.

Notes and Limitations
---------------------

[](#notes-and-limitations)

- Monitoring is request-based and depends on middleware execution.
- Failed MongoDB commands are currently not persisted.
- CLI/queue jobs are not tracked unless you manually wire monitoring for those flows.
- No migration is required because logs are inserted directly into MongoDB collection `performance_logs`.

Contributing
------------

[](#contributing)

Contributions are welcome and appreciated.

- Open an issue for bugs, questions, or feature requests.
- Submit a pull request for fixes, tests, or improvements.
- Improve documentation and examples to help other users.

If this package helps you, please consider starring the repository to support the project and help others discover it.

License
-------

[](#license)

MIT

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance86

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.7% 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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

91d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e3a21507d0cfedbf839cbcc5a8b060df87d8a2f6d39842a1e4aab47842394d71?d=identicon)[alloyking1](/maintainers/alloyking1)

---

Top Contributors

[![alloyking1](https://avatars.githubusercontent.com/u/22731000?v=4)](https://github.com/alloyking1 "alloyking1 (6 commits)")[![bskl](https://avatars.githubusercontent.com/u/9579731?v=4)](https://github.com/bskl "bskl (1 commits)")

### Embed Badge

![Health badge](/badges/mosesanu-laravel-mongodb-query-monitor/health.svg)

```
[![Health](https://phpackages.com/badges/mosesanu-laravel-mongodb-query-monitor/health.svg)](https://phpackages.com/packages/mosesanu-laravel-mongodb-query-monitor)
```

###  Alternatives

[psr/log

Common interface for logging libraries

10.4k1.2B10.9k](/packages/psr-log)[open-telemetry/api

API for OpenTelemetry PHP.

1938.5M261](/packages/open-telemetry-api)[open-telemetry/sdk

SDK for OpenTelemetry PHP.

2326.5M315](/packages/open-telemetry-sdk)[illuminated/console-logger

Logging and Notifications for Laravel Console Commands.

8676.7k](/packages/illuminated-console-logger)

PHPackages © 2026

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