PHPackages                             jupitern/cosmosdb - 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. jupitern/cosmosdb

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

jupitern/cosmosdb
=================

PHP wrapper for Azure Cosmos DB (formerly known as azure documentdb) using SQL rest api

2.7.3(2mo ago)1372.8k↓31.4%14[5 issues](https://github.com/jupitern/cosmosdb/issues)MITPHPPHP &gt;=8.0

Since Sep 27Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/jupitern/cosmosdb)[ Packagist](https://packagist.org/packages/jupitern/cosmosdb)[ Docs](https://github.com/jupitern/cosmosdb)[ RSS](/packages/jupitern-cosmosdb/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (2)Versions (34)Used By (0)

cosmosdb
========

[](#cosmosdb)

PHP wrapper for Azure Cosmos DB

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

[](#installation)

Include jupitern/cosmosdb in your project, by adding it to your composer.json file.

```
{
    "require": {
        "jupitern/cosmosdb": "2.*"
    }
}
```

Changelog
---------

[](#changelog)

### v2.7.0

[](#v270)

- adding support for PATCH verb (CosmosDb add-on PATCH API) with Add, Set, Replace, Remove, Increment and Move operations, including "getPatchOp\[OP\]" helper functions

### v2.6.0

[](#v260)

- code refactor. min PHP verion supported is now 8.0
- selectCollection no longer creates a colletion if not exist. use createCollection for that
- bug fixes

### v2.5.0

[](#v250)

- support partitioned queries using new method "setPartitionValue()"
- support creating partitioned collections
- support for nested partition keys

### v2.0.0

[](#v200)

- support for cross partition queries
- selectCollection method removed from all methods for performance improvements

### v1.4.4

[](#v144)

- replaced pear package http\_request2 by guzzle
- added method to provide guzzle configuration

### v1.3.0

[](#v130)

- added support for parameterized queries

Note
----

[](#note)

This package adds additional functionalities to the [AzureDocumentDB-PHP](https://github.com/cocteau666/AzureDocumentDB-PHP) package. All other functionality exists in this package as well.

Limitations
-----------

[](#limitations)

- Use of `limit()` or `order()` in cross-partition queries is currently not supported.
- Multi-document patch using transaction based requests is currently not supported.

Usage
-----

[](#usage)

### Connecting

[](#connecting)

```
$conn = new \Jupitern\CosmosDb\CosmosDb('https://localhost:8081', 'primaryKey');
$conn->setHttpClientOptions(['verify' => false]); # optional: set guzzle client options.
$db = $conn->selectDB('testdb');

# create a new collection
$collection = $db->createCollection('Users', 'country');

# select existing collection
$collection = $db->selectCollection('Users');
```

### Inserting Records

[](#inserting-records)

```
$rid = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->setPartitionKey('country')
    ->save([
        'id' => '2',
        'name' => 'Jane doe',
        'age' => 35,
        'country' => 'Portugal'
    ]);
```

### Updating Records

[](#updating-records)

```
$rid = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->setPartitionKey('country')
    ->save([
        "_rid" => $rid,
        'id' => '2',
        'name' => 'Jane Doe Something',
        'age' => 36,
        'country' => 'Portugal'
    ]);
```

### Patching Records

[](#patching-records)

```
# Patch operations: ADD | SET | REPLACE | REMOVE | INCR | MOVE
# https://learn.microsoft.com/en-us/azure/cosmos-db/partial-document-update#similarities-and-differences

# Where a PartitionKey is in use, the PartitionValue should be set on the QueryBuilder instance
# prior to making any PATCH operations, as by the nature of PATCH, there is no document body to find the value in,
# and the value is taken from the class property when the request is made. $rid_doc is also required because PATCH is an item-level operation.

# Example starting document (as array)

# [
# 	"_rid" => $rid,
# 	'id' => '2',
# 	'name' => 'Jane Doe Something',
# 	'age' => 36,
# 	'country' => 'Portugal'
# ]

$res = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->setPartitionKey('country')
    ->setPartitionValue('Portugal');

# Patch operations can be batched, so the $operations argument is an array of arrays
# Batch patch operations are limited to 10 operations per request
$operations[] = $res->getPatchOpSet('/age', 38);
$operations[] = $res->getPatchOpAdd('/region' 'Algarve');

$rid_doc = $res->patch($rid_doc, $operations);

# Example patched document (as array)

# [
# 	"_rid" => $rid,
# 	'id' => '2',
# 	'name' => 'Jane Doe Something',
# 	'age' => 38,
# 	'country' => 'Portugal'
#	'region' => 'Algarve'
# ]
```

### Querying Records

[](#querying-records)

```
# cross partition query to get a single document and return it as an array
$res = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->select("c.id, c.name")
    ->where("c.age > @age and c.country = @country")
    ->params(['@age' => 10, '@country' => 'Portugal'])
    ->find(true) # pass true if is cross partition query
    ->toArray();

# query a document using a known partition value
# and return as an array. note: setting a known
# partition value will result in a more efficient
# query against your database as it will not rely
# on cross-partition querying
$res = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->setPartitionValue('Portugal')
    ->select("c.id, c.name")
    ->where("c.age > @age")
    ->params(['@age' => 10])
    ->find()
    ->toArray();

# query to get the top 5 documents as an array, with the
# document ID as the array key.
# note: refer to limitations section
$res = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->select("c.id, c.name")
    ->where("c.age > @age and c.country = @country")
    ->params(['@age' => 10, '@country' => 'Portugal'])
    ->limit(5)
    ->findAll()
    ->toArray('id');

# query a document using a collection alias and cross partition query
$res = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->select("TestColl.id, TestColl.name")
    ->from("TestColl")
    ->where("TestColl.age > @age")
    ->params(['@age' => 10])
    ->findAll(true) # pass true if is cross partition query
    ->toArray();
```

### Deleting Records

[](#deleting-records)

```
# delete one document that matches criteria (single partition)
$res = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->setPartitionKey('country')
    ->where("c.age > 20 and c.country = 'Portugal'")
    ->delete();

# delete all documents that match criteria (cross partition)
$res = \Jupitern\CosmosDb\QueryBuilder::instance()
    ->setCollection($collection)
    ->setPartitionKey('country')
    ->where("c.age > 20")
    ->deleteAll(true);
```

### Error handling

[](#error-handling)

```
try {
    $res = QueryBuilder::instance()
        ->setCollection($collection)
        ->deleteAll(true);

} catch (\GuzzleHttp\Exception\ClientException $e) {
    $response = json_decode($e->getResponse()->getBody());
    echo "ERROR: ".$response->code ." => ". $response->message .PHP_EOL.PHP_EOL;

    echo $e->getTraceAsString();
}
```

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

[](#contributing)

- welcome to discuss a bugs, features and ideas.

License
-------

[](#license)

jupitern/cosmosdb is release under the MIT license.

You are free to use, modify and distribute this software, as long as the copyright header is left intact

###  Health Score

58

—

FairBetter than 98% of packages

Maintenance77

Regular maintenance activity

Popularity41

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity79

Established project with proven stability

 Bus Factor1

Top contributor holds 53.1% 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 ~89 days

Recently: every ~352 days

Total

32

Last Release

77d ago

Major Versions

1.5.0 → 2.0.02018-12-17

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

2.6.0PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/8205aca1dd2a7d1f98452950c3754b7430d16bcfe53494bfdf5c20d277d7776c?d=identicon)[jupitern](/maintainers/jupitern)

---

Top Contributors

[![jupitern](https://avatars.githubusercontent.com/u/4422374?v=4)](https://github.com/jupitern "jupitern (17 commits)")[![phuze](https://avatars.githubusercontent.com/u/9218035?v=4)](https://github.com/phuze "phuze (6 commits)")[![mdb-brevis](https://avatars.githubusercontent.com/u/70892846?v=4)](https://github.com/mdb-brevis "mdb-brevis (2 commits)")[![ppaulis](https://avatars.githubusercontent.com/u/1609503?v=4)](https://github.com/ppaulis "ppaulis (1 commits)")[![rioriost](https://avatars.githubusercontent.com/u/5734434?v=4)](https://github.com/rioriost "rioriost (1 commits)")[![SwanVods](https://avatars.githubusercontent.com/u/51660797?v=4)](https://github.com/SwanVods "SwanVods (1 commits)")[![ejunker](https://avatars.githubusercontent.com/u/4758?v=4)](https://github.com/ejunker "ejunker (1 commits)")[![TCB13](https://avatars.githubusercontent.com/u/6315832?v=4)](https://github.com/TCB13 "TCB13 (1 commits)")[![eouy](https://avatars.githubusercontent.com/u/1546910?v=4)](https://github.com/eouy "eouy (1 commits)")[![mrahmadt](https://avatars.githubusercontent.com/u/957921?v=4)](https://github.com/mrahmadt "mrahmadt (1 commits)")

---

Tags

cosmosdbdocumentdbazure cosmosdbazure documentdbcosmosdb restcosmosdb sql api rest

### Embed Badge

![Health badge](/badges/jupitern-cosmosdb/health.svg)

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

###  Alternatives

[aws/aws-sdk-php

AWS SDK for PHP - Use Amazon Web Services in your PHP project

6.2k543.5M2.7k](/packages/aws-aws-sdk-php)[leantime/leantime

Open source project management system for non-project managers. Simple like Trello, powerful like Jira. Built with neurodiversity in mind.

10.2k4.0k](/packages/leantime-leantime)[neuron-core/neuron-ai

The PHP Agentic Framework.

2.0k656.1k46](/packages/neuron-core-neuron-ai)[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3661.3M47](/packages/tencentcloud-tencentcloud-sdk-php)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

293.1k](/packages/eslazarev-wildberries-sdk)

PHPackages © 2026

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