Collection
Operations scoped to a single ArangoDB collection.
Instances are obtained through Database::collection() and share
the parent database's HTTP transport. The collection name is fixed at
construction time and is automatically interpolated into the
/_api/document/{name} and /_api/collection/{name} routes.
Every write method (insert(), update(), replace(), remove())
returns a Document built from the server response. By default
that document only carries the reserved _key / _id / _rev
attributes — pass returnNew: true (or returnOld: true on
remove()) in the options to receive the full payload, which is then
merged into the resulting Document.
Example:
$users = $db->collection( 'users' ) ;
$marc = $users->insert( [ 'name' => 'Marc' ] , [ 'returnNew' => true ] ) ;
echo $marc->getKey() ;
echo $marc->get( 'name' ) ; // 'Marc' (because of returnNew)
if ( $users->documentExists( $marc->getKey() ) )
{
$users->update( $marc->getKey() , [ 'role' => 'admin' ] ) ;
}
Tags
Table of Contents
Constants
- COLLECTION_QUERY_PARAM : string = 'collection'
- Query parameter accepted by `/_api/index` and `/_api/document` to scope a request to a specific collection.
- IMPORT_CONTENT_TYPE : string = 'application/x-ldjson'
- Content-Type sent on `/_api/import` requests. JSON Lines (one JSON document per line) is the standard wire format for this endpoint.
- IMPORT_TYPE_DOCUMENTS : string = 'documents'
- Value sent for the `type` query parameter of `/_api/import` when the payload is a JSON Lines stream of full documents (one JSON object per line). The legacy `array` / `auto` formats are not exposed by this client.
- IMPORT_TYPE_QUERY_PARAM : string = 'type'
- Name of the `type` query parameter on `/_api/import`.
Properties
Methods
- __construct() : mixed
- all() : Cursor
- Returns a {@see Cursor} iterating over every document of the collection.
- byExample() : Cursor
- Returns a {@see Cursor} iterating over documents that match every key/value pair of `$example` (equality match — for richer predicates, drop down to {@see Database::query()} and write the AQL by hand).
- count() : int
- Returns the current number of documents in the collection.
- create() : void
- Creates this collection on the server.
- createIndex() : array<string, mixed>
- Creates a secondary index on this collection.
- document() : Document
- Fetches a single document by key.
- documentExists() : bool
- Returns true when a document with the given key exists in this collection.
- drop() : void
- Drops this collection from the server.
- dropIndex() : void
- Drops an index from this collection.
- exists() : bool
- Returns true when this collection exists on the server.
- firstExample() : Document|null
- Returns the first document matching every key/value pair of `$example` (equality match), or `null` when no document matches.
- getName() : string
- Returns the collection name this instance is bound to.
- import() : ImportResult
- Bulk-imports an array of documents through the dedicated `POST /_api/import` endpoint.
- index() : array<string, mixed>
- Returns the server-side metadata of a single index.
- indexes() : array<int, array<string, mixed>>
- Returns the list of indexes defined on this collection.
- insert() : Document
- Inserts a new document into the collection.
- properties() : array<string, mixed>
- Returns the full server-side metadata of this collection (`GET /_api/collection/{name}/properties`).
- remove() : Document
- Removes a document by key.
- removeAll() : array<int, Document>
- Removes multiple documents from the collection in a single round-trip.
- rename() : static
- Renames the collection on the server and returns a NEW instance of the same class (`static`) bound to the new name. The current instance keeps pointing at the old name and should be discarded once `rename()` returns.
- replace() : Document
- Replaces an existing document with the given payload (PUT semantics).
- replaceAll() : array<int, Document>
- Replaces multiple documents in a single round-trip.
- saveAll() : array<int, Document>
- Inserts multiple documents in a single round-trip.
- truncate() : void
- Truncates the collection (removes every document, keeps the collection itself).
- update() : Document
- Partially updates an existing document with the given partial payload (PATCH semantics — only the supplied fields are touched).
- updateAll() : array<int, Document>
- Partially updates multiple documents in a single round-trip (PATCH semantics — only the supplied fields are touched on each document).
- collectionPath() : string
- Builds the `/_api/collection/{name}{suffix}` path with the collection name URL-encoded. `$suffix` is concatenated as-is and is expected to be one of the {@see CollectionRoute} constants (or an empty string to target the collection itself).
- documentPath() : string
- Builds the `/_api/document/{collection}/{key}` path with both segments URL-encoded.
- wrapWritten() : Document
- Wraps a write-operation response body into a {@see Document}.
- wrapWrittenBatch() : array<int, Document>
- Wraps a batched write-operation response body into an array of {@see Document} instances — one per row of the response, in the order the server emitted them.
Constants
COLLECTION_QUERY_PARAM
Query parameter accepted by `/_api/index` and `/_api/document` to scope a request to a specific collection.
private
string
COLLECTION_QUERY_PARAM
= 'collection'
IMPORT_CONTENT_TYPE
Content-Type sent on `/_api/import` requests. JSON Lines (one JSON document per line) is the standard wire format for this endpoint.
private
string
IMPORT_CONTENT_TYPE
= 'application/x-ldjson'
IMPORT_TYPE_DOCUMENTS
Value sent for the `type` query parameter of `/_api/import` when the payload is a JSON Lines stream of full documents (one JSON object per line). The legacy `array` / `auto` formats are not exposed by this client.
private
string
IMPORT_TYPE_DOCUMENTS
= 'documents'
IMPORT_TYPE_QUERY_PARAM
Name of the `type` query parameter on `/_api/import`.
private
string
IMPORT_TYPE_QUERY_PARAM
= 'type'
Properties
$database
public
Database
$database
$name
public
string
$name
Methods
__construct()
public
__construct(Database $database, string $name) : mixed
Parameters
- $database : Database
-
Parent database (provides the shared HTTP transport).
- $name : string
-
Name of the target collection on the server.
all()
Returns a {@see Cursor} iterating over every document of the collection.
public
all([int $limit = 0 ][, int $offset = 0 ]) : Cursor
Backed by a plain FOR doc IN @@col RETURN doc AQL query (the
/_api/simple/all endpoint was deprecated in ArangoDB 3.x).
Pagination is applied through optional LIMIT clauses — only
non-zero values are emitted, so the default behaviour fetches
the whole collection in lazy batches.
Equivalent to byExample([], $limit, $offset).
Parameters
- $limit : int = 0
-
Maximum number of documents to return (
0= no LIMIT). - $offset : int = 0
-
Number of documents to skip before returning results (
0= no offset). Named after the AQL nativeLIMIT offset, countsyntax.
Tags
Return values
CursorbyExample()
Returns a {@see Cursor} iterating over documents that match every key/value pair of `$example` (equality match — for richer predicates, drop down to {@see Database::query()} and write the AQL by hand).
public
byExample(array<string, mixed> $example[, int $limit = 0 ][, int $offset = 0 ]) : Cursor
Backed by a FOR doc IN @@col [FILTER doc.k1 == @v1 AND …] RETURN doc
AQL query (the /_api/simple/by-example endpoint was deprecated
in ArangoDB 3.x).
To avoid AQL injection through example keys, each key is
validated against /^[a-zA-Z_][a-zA-Z0-9_.]*$/ — simple
top-level attributes and dotted paths (address.city) are
supported, anything else throws an
InvalidArgumentException. Example values are always
passed as bind variables and never inlined.
Parameters
- $example : array<string, mixed>
-
Equality predicate (empty array = no FILTER).
- $limit : int = 0
-
Maximum number of documents to return (
0= no LIMIT). - $offset : int = 0
-
Number of documents to skip before returning results (
0= no offset). Named after the AQL nativeLIMIT offset, countsyntax.
Tags
Return values
Cursorcount()
Returns the current number of documents in the collection.
public
count() : int
Tags
Return values
intcreate()
Creates this collection on the server.
public
create([array<string, mixed> $options = [] ]) : void
The collection name is taken from $name; the type defaults
to CollectionType::DOCUMENT when the caller does not set
it explicitly through $options. Subclasses targeting another
collection type (e.g. EdgeCollection) override this method
to substitute a different default.
Any extra option is forwarded as-is to the server's
POST /_api/collection endpoint (waitForSync, keyOptions,
numberOfShards, replicationFactor, writeConcern,
cacheEnabled, …).
Parameters
- $options : array<string, mixed> = []
-
Extra creation options.
Tags
createIndex()
Creates a secondary index on this collection.
public
createIndex(IndexDefinition $definition) : array<string, mixed>
Parameters
- $definition : IndexDefinition
-
Index definition built from one of the indexes value objects (PersistentIndex, GeoIndex, TtlIndex, FulltextIndex, …).
Tags
Return values
array<string, mixed> —Raw server response (carries the assigned id, the resolved type, the indexed fields, …).
document()
Fetches a single document by key.
public
document(string $key) : Document
Parameters
- $key : string
-
The document key (
_key).
Tags
Return values
DocumentdocumentExists()
Returns true when a document with the given key exists in this collection.
public
documentExists(string $key) : bool
Uses an HTTP HEAD request (no body) so the round-trip stays cheap. Any non-404 error is rethrown as an ArangoException.
Parameters
- $key : string
-
The document key.
Tags
Return values
booldrop()
Drops this collection from the server.
public
drop() : void
Tags
dropIndex()
Drops an index from this collection.
public
dropIndex(string $idOrName) : void
Accepts either a full server-side handle (users/12345 or
users/idx_email_unique) or just the key / name part (12345,
idx_email_unique) — the collection name is prefixed
automatically when missing.
Parameters
- $idOrName : string
-
Full handle or key/name of the index to drop.
Tags
exists()
Returns true when this collection exists on the server.
public
exists() : bool
Issues GET /_api/collection/{name} and treats a 404 as a clean
"missing" — any other failure is rethrown as an
ArangoException.
Tags
Return values
boolfirstExample()
Returns the first document matching every key/value pair of `$example` (equality match), or `null` when no document matches.
public
firstExample(array<string, mixed> $example) : Document|null
Shortcut over byExample() that materialises the first row
of the result cursor into a Document. The key validation
rules from byExample() apply.
Parameters
- $example : array<string, mixed>
-
Equality predicate.
Tags
Return values
Document|nullgetName()
Returns the collection name this instance is bound to.
public
getName() : string
Return values
stringimport()
Bulk-imports an array of documents through the dedicated `POST /_api/import` endpoint.
public
import(array<int, array<string, mixed>> $documents[, array<string, mixed> $options = [] ]) : ImportResult
Around 100× faster than saveAll() on large batches because
the server skips the per-document parser / response builder and
streams the input directly into the storage engine. The trade-off
is that partial failures do not surface as per-row Document
instances — the server returns aggregated counters
(created / errors / empty / updated / ignored), exposed
here as an ImportResult.
Each entry of $documents must be an associative array; objects
are not accepted at this layer (call ->toArray() on the
caller's side, or use saveAll() which returns typed
Document instances).
Server-side options are forwarded as query parameters (booleans
are stringified to the spelling Arango expects). Recognised keys
include overwrite (truncate the target before importing),
waitForSync, complete (abort on first error), details
(populate ImportResult::$details), onDuplicate (one of
the OnDuplicate constants), fromPrefix, toPrefix.
Example:
$result = $users->import
(
[
[ '_key' => 'alice' , 'name' => 'Alice' ] ,
[ '_key' => 'bob' , 'name' => 'Bob' ] ,
] ,
[
'waitForSync' => true ,
'onDuplicate' => OnDuplicate::UPDATE ,
'details' => true ,
] ,
) ;
if ( $result->hasErrors() )
{
foreach ( $result->details as $message ) { error_log( $message ) ; }
}
Parameters
- $documents : array<int, array<string, mixed>>
-
Documents to import.
- $options : array<string, mixed> = []
-
Server-side options (
overwrite,waitForSync,complete,details,onDuplicate,fromPrefix,toPrefix, …).
Tags
Return values
ImportResultindex()
Returns the server-side metadata of a single index.
public
index(string $idOrName) : array<string, mixed>
Accepts either a full server-side handle (users/12345 or
users/idx_email) or just the key / name part (12345,
idx_email) — the collection name is prefixed automatically
when missing.
Parameters
- $idOrName : string
-
Full handle or key/name of the index.
Tags
Return values
array<string, mixed> —Raw server response (id, type, fields, …).
indexes()
Returns the list of indexes defined on this collection.
public
indexes() : array<int, array<string, mixed>>
Each entry is the raw server-side metadata (id, type, fields, …);
IndexField constants can be used to read its keys safely.
Tags
Return values
array<int, array<string, mixed>>insert()
Inserts a new document into the collection.
public
insert(array<string, mixed> $data[, array<string, mixed> $options = [] ]) : Document
The returned Document carries the server-assigned
_key / _id / _rev; pass returnNew: true in $options to
receive the full inserted payload merged into the result.
Parameters
- $data : array<string, mixed>
-
Document payload.
- $options : array<string, mixed> = []
-
Server-side options (
returnNew,waitForSync,overwriteMode, …).
Tags
Return values
Documentproperties()
Returns the full server-side metadata of this collection (`GET /_api/collection/{name}/properties`).
public
properties() : array<string, mixed>
The response is returned as a raw associative array — fields
include the canonical CollectionField entries (name,
isSystem, type, …) plus the type-specific details (keyOptions,
numberOfShards, replicationFactor, writeConcern,
cacheEnabled, globallyUniqueId, id, status, …).
Tags
Return values
array<string, mixed>remove()
Removes a document by key.
public
remove(string $key[, array<string, mixed> $options = [] ]) : Document
The returned Document carries the meta returned by the
server (_key / _id / _rev); pass returnOld: true in
$options to receive the deleted payload merged into the result.
Parameters
- $key : string
-
Document key.
- $options : array<string, mixed> = []
-
Server-side options (
returnOld,waitForSync, …).
Tags
Return values
DocumentremoveAll()
Removes multiple documents from the collection in a single round-trip.
public
removeAll(array<int, string|array<string, mixed>> $selectors[, array<string, mixed> $options = [] ]) : array<int, Document>
$selectors accepts either raw keys (strings) or objects carrying
_key / _id — both forms are forwarded as-is to ArangoDB in the
request body of DELETE /_api/document/{collection}.
The server processes the array entry-by-entry: each entry produces
an entry in the response array, either the deleted meta
(_key / _id / _rev plus optional old payload when
returnOld: true) or an error object (error: true,
errorNum, errorMessage). Partial failures do not abort the
batch — the caller inspects each returned Document to
decide what to do.
Parameters
- $selectors : array<int, string|array<string, mixed>>
-
Document keys or
{_key, …}/{_id, …}objects. - $options : array<string, mixed> = []
-
Server-side options (
returnOld,waitForSync,silent,ignoreRevs,refillIndexCaches, …).
Tags
Return values
array<int, Document> —One entry per input selector, same order as the input.
rename()
Renames the collection on the server and returns a NEW instance of the same class (`static`) bound to the new name. The current instance keeps pointing at the old name and should be discarded once `rename()` returns.
public
rename(string $newName) : static
Cluster note: ArangoDB rejects rename operations on cluster deployments (only single-server setups support it). The error is surfaced as an ArangoException.
Parameters
- $newName : string
-
New collection name.
Tags
Return values
static —New instance bound to $newName.
replace()
Replaces an existing document with the given payload (PUT semantics).
public
replace(string $key, array<string, mixed> $data[, array<string, mixed> $options = [] ]) : Document
Parameters
- $key : string
-
Document key.
- $data : array<string, mixed>
-
Replacement payload.
- $options : array<string, mixed> = []
-
Server-side options (
returnNew,returnOld,ignoreRevs,waitForSync, …).
Tags
Return values
DocumentreplaceAll()
Replaces multiple documents in a single round-trip.
public
replaceAll(array<int, array<string, mixed>> $documents[, array<string, mixed> $options = [] ]) : array<int, Document>
Each entry of $documents must carry the _key (or _id) of
the target document; the rest of the payload becomes the new
content of that document (PUT semantics — fields absent from
the payload are dropped).
The server processes the array entry-by-entry: each entry
produces an entry in the response array, either the meta
(_key / _id / _rev + optional new / old) or an error
object (error: true, errorNum, errorMessage). Partial
failures do not abort the batch.
Parameters
- $documents : array<int, array<string, mixed>>
-
Replacement payloads (each MUST include
_keyor_id). - $options : array<string, mixed> = []
-
Server-side options (
returnNew,returnOld,ignoreRevs,silent,waitForSync, …).
Tags
Return values
array<int, Document> —One entry per input document, same order as the input.
saveAll()
Inserts multiple documents in a single round-trip.
public
saveAll(array<int, array<string, mixed>> $documents[, array<string, mixed> $options = [] ]) : array<int, Document>
Each entry of $documents is treated as a brand-new document
(POST semantics). The server processes the array entry-by-entry:
each entry produces an entry in the response array, either the
inserted meta (_key / _id / _rev + optional new) or an
error object (error: true, errorNum, errorMessage).
Partial failures do not abort the batch.
Parameters
- $documents : array<int, array<string, mixed>>
-
Documents to insert.
- $options : array<string, mixed> = []
-
Server-side options (
returnNew,overwriteMode,keepNull,mergeObjects,silent,waitForSync, …).
Tags
Return values
array<int, Document> —One entry per input document, same order as the input.
truncate()
Truncates the collection (removes every document, keeps the collection itself).
public
truncate() : void
Tags
update()
Partially updates an existing document with the given partial payload (PATCH semantics — only the supplied fields are touched).
public
update(string $key, array<string, mixed> $partial[, array<string, mixed> $options = [] ]) : Document
Parameters
- $key : string
-
Document key.
- $partial : array<string, mixed>
-
Partial payload.
- $options : array<string, mixed> = []
-
Server-side options (
returnNew,returnOld,keepNull,mergeObjects, …).
Tags
Return values
DocumentupdateAll()
Partially updates multiple documents in a single round-trip (PATCH semantics — only the supplied fields are touched on each document).
public
updateAll(array<int, array<string, mixed>> $patches[, array<string, mixed> $options = [] ]) : array<int, Document>
Each entry of $patches must carry the _key (or _id) of the
target document; the rest of the payload is merged into that
document on the server.
The server processes the array entry-by-entry: each entry
produces an entry in the response array, either the meta
(_key / _id / _rev + optional new / old) or an error
object (error: true, errorNum, errorMessage). Partial
failures do not abort the batch.
Parameters
- $patches : array<int, array<string, mixed>>
-
Patch payloads (each MUST include
_keyor_id). - $options : array<string, mixed> = []
-
Server-side options (
returnNew,returnOld,keepNull,mergeObjects,ignoreRevs,silent,waitForSync, …).
Tags
Return values
array<int, Document> —One entry per input patch, same order as the input.
collectionPath()
Builds the `/_api/collection/{name}{suffix}` path with the collection name URL-encoded. `$suffix` is concatenated as-is and is expected to be one of the {@see CollectionRoute} constants (or an empty string to target the collection itself).
private
collectionPath([string $suffix = '' ]) : string
Parameters
- $suffix : string = ''
-
Sub-route suffix (typically a CollectionRoute constant, e.g.
/count).
Return values
stringdocumentPath()
Builds the `/_api/document/{collection}/{key}` path with both segments URL-encoded.
private
documentPath(string $key) : string
Parameters
- $key : string
-
Document key (
_key).
Return values
stringwrapWritten()
Wraps a write-operation response body into a {@see Document}.
private
wrapWritten(mixed $body, string $payloadField) : Document
When the server returned the optional new / old payload (because
returnNew / returnOld was set), it is merged into the resulting
document data, with the server-assigned reserved attributes
(_key / _id / _rev) taking precedence.
Parameters
- $body : mixed
-
Decoded response body.
- $payloadField : string
-
Key of the optional payload field (
newfor insert/update/replace,oldfor remove).
Return values
DocumentwrapWrittenBatch()
Wraps a batched write-operation response body into an array of {@see Document} instances — one per row of the response, in the order the server emitted them.
private
wrapWrittenBatch(mixed $body, string $payloadField) : array<int, Document>
Each entry of the response can be either a success meta (the
usual _key / _id / _rev + optional new / old payload)
or a per-row error object (error: true, errorNum,
errorMessage). Both shapes flow through the existing
wrapWritten() so callers can use the typed
Document API to introspect either case (e.g.
$doc->get('error') === true to detect a failed row).
Parameters
- $body : mixed
-
Decoded response body — expected to be a list of entries.
- $payloadField : string
-
Key of the optional payload field (
newfor insert/update/replace,oldfor remove).