---
title: Scopes and Collections
pubDate: 2026-10-03T04:27:21.374Z
meta:
  component:
    title: Couchbase Lite React Native
    version: "1.1"
antora:
  editUrl: https://github.com/couchbaselabs/docs-couchbase-lite-react-native/edit/release/1.1/modules/ROOT/pages/scopes-collections.adoc
  xref: xref:cbl-reactnative::scopes-collections.adoc[]
---

[Consult the llms.txt file for a full list of contents](/llms.txt)
[View original HTML](/cbl-reactnative/current/scopes-collections.html)

# Scopes and Collections

> Description - _Scopes and collections allow you to organize your documents within a database._

> [!IMPORTANT]
> AT A GLANCE
> 
> **Use collections to organize your content in a database**
> 
> For example, if your database contains travel information, airport documents can be assigned to an airports collection, hotel documents can be assigned to a hotels collection, and so on.
> 
> * Document names must be unique within their collection.
> 
> **Use scopes to group multiple collections**
> 
> Collections can be assigned to different scopes according to content-type or deployment-phase (for example, test versus production).
> 
> * Collection names must be unique within their scope.
> 
> Unlike Couchbase Server and Capella, a scope cannot exist without a collection, thus there is no API to create a scope. Instead, use the collection API to create a collection in a scope and the scope is created from that API.

## [](#default-scopes-and-collections)Default Scopes and Collections

Every database you create contains a default scope and a default collection named `_default`.

If you create a document in the database and don't specify a specific scope or collection, it is saved in the default collection, in the default scope.

If you upgrade from a version of Couchbase Lite prior to support for scops and collections, all existing data is automatically placed in the default scope and default collection.

The default scope and collection cannot be dropped.

## [](#create-a-scope-and-collection)Create a Scope and Collection

In addition to the default scope and collection, you can create your own scope and collection when you create a document.

Naming conventions for collections and scopes:

* Must be between 1 and 251 characters in length.
* Can only contain the characters `A-Z`, `a-z`, `0-9`, and the symbols `_`, `-`, and `%`.
* Cannot start with `_` or `%`.
* Scope names must be unique in databases.
* Collection names must be unique within a scope.

> [!NOTE]
> Scope and collection names are case sensitive.

**Example 1\. Create a scope and collection**

```typescript
const scopeName = "myScopeName";
const collectionName = "myCollectionName";
const collection = await database.createCollection(collectionName, scopeName);
```

In the example above, you can see that `Database.createCollection` can take two parameters. The second is the scope assigned to the created collection, if this parameter is omitted then a collection of the given name will be assigned to the `_default` scope.

The first parameter is the name of the collection you want to create, in this case `myCollectionName`.

If a collection with the specified name already exists in the specified scope, `Database.createCollection` returns the existing collection.

> [!NOTE]
> You cannot create an empty user-defined scope. A scope is implicitly created and removed by the `Database.createCollection` and `Database.deleteCollection` methods.

## [](#index-a-collection)Index a Collection

**Example 2\. Index a Collection**

```typescript
 // Define a value index on 'name' and 'documentType'
const valueIndex = IndexBuilder.valueIndex(
    ValueIndexItem.property('name'),
    ValueIndexItem.property('documentType')
);

// Create the value index
const valueIndexName = 'nameTypeIndex';
await collection.createIndex(valueIndexName, valueIndex);
```

## [](#drop-a-collection)Drop a Collection

**Example 3\. Drop a Collection**

```typescript
await database.deleteCollection(collectionName, scopeName);
```

## [](#list-scopes-and-collections)List Scopes and Collections

**Example 4\. List Scopes and Collections**

```typescript
// Get Scopes
const scopes = await database.scopes();

// Get Collections of a particular Scope
const collections = await database.collections(scopeName);
```

## [](#get-collection-full-name)Get Collection Full Name

The `fullName()` method returns the fully qualified name of a collection in the format "scope.collection".

The full name is useful for logging, debugging, and displaying collection information in your application.

**Example 5\. Get Collection Full Name**

```typescript
// User-defined collection
const collection = await database.createCollection('users', 'production');
const fullName = await collection.fullName();
console.log(fullName);
// Output: "production.users"

// Default collection
const defaultCol = await database.defaultCollection();
const defaultName = await defaultCol.fullName();
console.log(defaultName);
// Output: "_default._default"
```

## [](#collection-change-listeners)Collection Change Listeners

Monitor all changes to any document in a collection.

### [](#when-to-use)When to Use

* Refresh list views when data changes
* Trigger background sync after local updates
* Audit logging of collection activity
* Real-time collaboration features

### [](#data-structure)Data Structure

When a collection changes, your callback receives a `CollectionChange` object:

```typescript
interface CollectionChange {
  documentIDs: string[];  // Array of changed document IDs
  collection: Collection; // Reference to the collection
}
```

> [!CAUTION]
> Property Names
> 
> The property is `documentIDs` (capital IDs), not `documentIds`.
> 
> There is NO direct `database` property. Access it via `change.collection.database`.

#### [](#example-6-basic-collection-listener)Example 6\. Basic Collection Listener

```typescript
import { Collection, ListenerToken } from '@couchbase/couchbase-lite-react-native';

const collection = await database.createCollection('users');

const token: ListenerToken = await collection.addChangeListener((change) => {
  console.log('Collection changed!');
  console.log('Changed documents:', change.documentIDs);
  // Example output: ['user-123', 'user-456']

  console.log('Collection name:', change.collection.name);
  // Output: users

  console.log('Database name:', change.collection.database.getName());
  // Output: mydb
});

// Remove listener when done
await token.remove();
```

#### [](#example-7-react-hook-pattern)Example 7\. React Hook Pattern

```typescript
import { useEffect } from 'react';
import { ListenerToken } from '@couchbase/couchbase-lite-react-native';

function UserListScreen({ collection }) {
  useEffect(() => {
    if (!collection) return;

    let token;

    const setup = async () => {
      token = await collection.addChangeListener((change) => {
        console.log(`${change.documentIDs.length} documents changed`);
        refreshUserList();
      });
    };
    setup();

    // Cleanup on unmount
    return () => {
      if (token) token.remove();
    };
  }, [collection]);
}
```

> [!IMPORTANT]
> Limitation
> 
> Only ONE collection-wide listener is allowed per collection instance. Calling `addChangeListener` twice will throw an error.
> 
> However, you can have MULTIPLE document listeners on the same collection.

> [!CAUTION]
> Deprecated
> 
> The `collection.removeChangeListener(token)` method is deprecated. It remains available for backward compatibility, but new applications should use `token.remove()`. Existing applications are strongly encouraged to migrate.