PHPackages                             maer/mongo-query - 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. maer/mongo-query

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

maer/mongo-query
================

A basic query builder in PHP for mongo

0.2.1(2y ago)037MITPHPPHP &gt;=8.0

Since Oct 17Pushed 2y ago1 watchersCompare

[ Source](https://github.com/magnus-eriksson/mongo-query)[ Packagist](https://packagist.org/packages/maer/mongo-query)[ RSS](/packages/maer-mongo-query/feed)WikiDiscussions develop Synced 3d ago

READMEChangelogDependencies (1)Versions (7)Used By (0)

Mongo Query Builder for PHP
===========================

[](#mongo-query-builder-for-php)

Why? Because writing Mongo queries in PHP feels awkward and quickly becomes hard to read.

> This is still under development and the API might change until there's a 1.x-release.

***Note:*** This is just a wrapper for the `mongodb/mongodb`-library and you always have access to the underlying library if you want to do something this wrapper doesn't support.

Usage
-----

[](#usage)

- [Install](#install)
- [Simple example](#simple-example)
- [Query builder](#query-builder)
    - [Insert](#insert)
    - [Get data](#get-data)
        - [Get list of items](#get-list-of-items)
        - [Get first item](#get-first-item)
        - [Find](#find)
        - [Count](#count)
        - [Where](#where)
            - [Operators](#operators)
        - [Or where](#or-where)
        - [Order by](#order-by)
        - [Limit](#limit)
        - [Skip](#skip)
        - [Select](#skip)
        - [Update](#update)
        - [Replace](#replace)
        - [Delete](#delete)
- [Additional](#additional)
    - [The MongoDB instances](#the-mongodb-instances)

Install
-------

[](#install)

Clone this repository or use composer (recommended) to download the library with the following command:

```
composer require maer/mongo-query

```

Simple example
--------------

[](#simple-example)

```
// Load composers autoloader
include '/path/to/vendor/autoload.php';

// Instatiate with no arguments and a MongoDB\Client instance will be created
// (using localhost and default port)
$client = new Maer\MongoQuery\Connection();

// To use a custom client instance, pass it as the first argument
$client = $client = new Maer\MongoQuery\Connection(
    new MongoDB\Client('mongodb://example.com:1234')
);

// Get a database
$db = $client->myDatabase; // Or: $client->getDatabase('myDatabase');

// Get a collection
$collection = $db->myCollection; // Or: $db->getCollection('myCollection');

// Add some criterias
$result = $collection->where('some-key', 'some-value')
    ->orderBy('some-key', 'asc')
    ->get();

// $result will now contain an array with the matched documents
```

This was just a simple example. Read more below to find out more...

Query builder
-------------

[](#query-builder)

### Insert

[](#insert)

You can either insert one document

```
$id = $collection->insert([
    'some-key' => 'some-value',
]);

// $id contains the new id for the inserted document or false on error
```

or you can insert many in one go

```
$ids = $collection->insert([
    [
        'some-key' => 'some-value',
    ],
    [
        'some-key' => 'some-other-value',
    ]
]);

// $ids contains an array of the new ids for the inserted documents or false on error
```

### Get data

[](#get-data)

Most of the below items will return a multi dimensional array with the matching items.

#### Get list of items

[](#get-list-of-items)

```
$result = $collection->get();
```

#### Get first item

[](#get-first-item)

Return the first matched item.

```
$result = $collection->first();
```

#### Find

[](#find)

Get first item that matches a single condition.

```
// Find by _id (default)
$result = $collection->find('123');

// Find by some other key (is equal to)
$result = $collection->find('some-value', 'some-key');
```

This is the only "getter" that can't have any other criteria.

#### Count

[](#count)

To get the total count of matched documents, use:

```
$result = $collection->where('some-key', 'some-value')->count();
// $result is an integer with the number of matched documents
```

All methods that returns an actual result will also reset the query (remove any criteria previously added).

When it comes to `count()`, there might be situations where you don't want this (like when you build pagination). To keep all the criteria, you can pass `false` to the `count()`-method: `count(false)`.

If you pass `false`, you can do:

```
$result = $colletion->get();
```

and it will only return the documents that matched the previous criteria.

#### Where

[](#where)

Usually, you only want to return some specific items which match some type of criteria.

```
$result = $collection->where('some-key', 'some-value')->get();
```

The above will match all items that has `some-value` as the value for the key `some-key`. This equals: `where('some-key', '=', 'some-value')`.

##### Operators

[](#operators)

There are many more operators you can use to narrow down the result.

The below operators are used like this: `where($column, $operator, $value)`

OperatorDescription`=`Equal to`!=`Not equal to``Higher than`=`Higher or equal to`*`Contains`=*`Starts with`*=`Ends withYou can add as many where conditions as you like to the same query. To make it easier, you can chain them:

```
$result = $collection->where('some-key', '=', 'some-value')
    ->where('some-other-key', '!=', 'some-other-value')
    ...
    ->get();
```

#### Or Where

[](#or-where)

To add an or `$or`-block, use `orWhere()`:

```
$collection->orWhere('some-key', 'some-value')
    ->orWhere('some-other-key', 'some-other-value');

// Same as:
// [
//     '$or' => [
//         [
//             'some-key' => 'some-value',
//         ],
//         [
//             'some-other-key' => 'some-other-value'
//         ]
//     ],
// ]
```

You can also group the or-credentials:

```
$collection->orWhere(function ($query) {
    $query->where('some-key', 'some-value')
        ->where('some-other-key', 'some-other-value');
});

// Same as:
// [
//     '$or' => [
//         [
//             'some-key' => 'some-value',
//             'some-other-key' => 'some-other-value'
//         ]
//     ],
// ]
```

#### Order by

[](#order-by)

To sort the result in a specific way, you can use `orderBy(['column' => 'asc|desc'])`.

```
// Ascending order:
$result = $collection->orderBy(['first_name' => 'asc']);

// Descending order:
$result = $collection->orderBy(['first_name' => 'desc']);
```

#### Limit

[](#limit)

You can limit the amount of items returned.

```
// Only get the 2 first matches
$result = $collection->people->limit(2)->get();
```

#### Skip

[](#skip)

If you need to add an offset (for using with pagination, for example), you can define how many documents it should `skip()`:

```
// Get all results from the second match and forward.
$result = $collection->offset(2)->get();
```

#### Select

[](#select)

You might only want to fetch some specific fields from the documents. You can define what fields to get using `select()`

```
// Define what fields you want to get
$result = $collection->select(['some-key', 'some-other-key'])->get();
```

**Note:** This method will always return the `_id`-field as well

#### Pluck

[](#pluck)

If you only want to get one single field as an array with all the values, you can use `pluck()`

```
$result = $collection->pluck('some-key');

// Returns
// [
//     'first-value',
//     'second-value',
//     ...
// ]
```

Any potential duplicates will also be removed.

### Update

[](#update)

To update an item, use `updateOne(array $data)`:

```
$modified = $collection->where('some-key', 'some-value')
    ...
    ->updateOne([
        'some-key' => 'some-new-value',
    ]);
```

To update multiple items, use `updateMany(array $data)`:

```
$modified = $collection->where('some-key', 'some-value')
    ...
    ->updateMany([
        'some-key' => 'some-new-value',
    ]);
```

These method returns the number of modified documents.

When updating, you only need to pass the fields and values you want to update. All other values will remain as is in the database.

### Replace

[](#replace)

The difference between these methods and the update, is that these replaces the complete documents, except from the \_id. Example:

```
$modified = $collection->insert([
    'foo'     => 'Lorem',
    'bar'     => 'Ipsum',
]);

$modified = $collection->where('foo', 'Lorem')
    ->replaceOne([
        'foo_bar' => 'Lorem Ipsum',
    ]);

$result = $collection->first();
// Returns:
// [
//     '_id'      => xxx,
//     'foo_bar' => 'Lorem Ipsum',
// ]
```

### Delete

[](#delete)

Delete items

```
$result = $collection->where('some-key', 'some-value')
    ->deleteOne();
```

To delete multiple items, use `deleteMany()`.

These methods returns the number of modified documents.

Additional
----------

[](#additional)

### The MongoDB instances

[](#the-mongodb-instances)

Sometimes you want to do some magic that this library doesn't support (yet). To do that, you might need to access the underlying MongoDB instances. You can do that with the `getInstance()`-methods.

```
$mongo = new Maer\MongoQuery\Connection;

// Get MongoDB\Client
$client = $mongo->getClient();

// Get MongoDB\Database
$database = $mongo->someDatabase->getDatabase();

// Get MongoDB\Collection
$collection = $mongo->someDatabase->someCollection->getCollection();
```

---

If you have any questions, suggestions or issues, let me know!

Happy coding!

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity61

Established project with proven stability

 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.

###  Release Activity

Cadence

Every ~453 days

Total

5

Last Release

953d ago

PHP version history (2 changes)0.1.0PHP &gt;=7.0

0.2.0PHP &gt;=8.0

### Community

Maintainers

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

---

Top Contributors

[![magnus-eriksson](https://avatars.githubusercontent.com/u/3640297?v=4)](https://github.com/magnus-eriksson "magnus-eriksson (8 commits)")

### Embed Badge

![Health badge](/badges/maer-mongo-query/health.svg)

```
[![Health](https://phpackages.com/badges/maer-mongo-query/health.svg)](https://phpackages.com/packages/maer-mongo-query)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[doctrine/mongodb-odm

PHP Doctrine MongoDB Object Document Mapper (ODM) provides transparent persistence for PHP objects to MongoDB.

1.1k23.3M302](/packages/doctrine-mongodb-odm)[alcaeus/mongo-php-adapter

Adapter to provide ext-mongo interface on top of mongo-php-library

46412.3M73](/packages/alcaeus-mongo-php-adapter)[moloquent/moloquent

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

120114.6k7](/packages/moloquent-moloquent)[doesntmattr/mongodb-migrations

Managed Database Migrations for MongoDB

23598.7k1](/packages/doesntmattr-mongodb-migrations)[facile-it/mongodb-bundle

Bundle service integration of official \[mongodb/mongo-php-library\](https://github.com/mongodb/mongo-php-library) driver library

38212.1k1](/packages/facile-it-mongodb-bundle)

PHPackages © 2026

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