A collection stores documents of the same type.

Creating a Collection

To create one or more collections you need a RxDatabase object which has the .addCollections()-method. Every collection needs a collection name and a valid RxSchema. Other attributes are optional.

const myCollection = await myDatabase.addCollections({
  // key = collectionName
  humans: {
    schema: mySchema,
    pouchSettings: {}, // (optional)
    statics: {}, // (optional) ORM-functions for this collection
    methods: {}, // (optional) ORM-functions for documents
    attachments: {}, // (optional) ORM-functions for attachments
    options: {}, // (optional) Custom parameters that might be used in plugins
    migrationStrategies: {}, // (optional)
    autoMigrate: true, // (optional)
    cacheReplacementPolicy: function(){}, // (optional) custom cache replacement policy
  // you can create multiple collections at once
  otherHumans: {
    // ...


The name uniquely identifies the collection and should be used to refind the collection in the database. Two different collections in the same database can never have the same name. Collection names must match the following regex: ^[a-z][a-z0-9]*$.


The schema defines how your data looks and how it should be handled. You can pass a RxSchema object or a simple javascript-object from which the schema will be generated.


You can pass settings directly to the pouchdb database create options through this property.


With the parameters statics, methods and attachments, you can define ORM-functions that are applied to each of these objects that belong to this collection. See ORM/DRM.


With the parameters migrationStrategies and autoMigrate you can specify how migration between different schema-versions should be done. See Migration.

Get a collection from the database

To get an existing collection from the database, call the collection name directly on the database:

// newly created collection
const collections = await db.addCollections({
  heroes: {
    schema: mySchema
const collection2 = db.heroes;
console.log(collections.heroes === collection2); //> true


Observe $

Calling this will return an rxjs-Observable which streams every change to data of this collection.

myCollection.$.subscribe(changeEvent => console.dir(changeEvent));

// you can also observe single event-types with insert$ update$ remove$
myCollection.insert$.subscribe(changeEvent => console.dir(changeEvent));
myCollection.update$.subscribe(changeEvent => console.dir(changeEvent));
myCollection.remove$.subscribe(changeEvent => console.dir(changeEvent));


Use this to insert new documents into the database. The collection will validate the schema and automatically encrypt any encrypted fields. Returns the new RxDocument.

const doc = await myCollection.insert({
  name: 'foo',
  lastname: 'bar'


When you have to insert many documents at once, use bulk insert. This is much faster than calling .insert() multiple times. Returns an object with a success- and error-array.

const result = await myCollection.bulkInsert([{
  name: 'foo1',
  lastname: 'bar1'
  name: 'foo2',
  lastname: 'bar2'

// > {
//   success: [RxDocument, RxDocument],
//   error: []
// }

NOTICE: bulkInsert will not fail on update conflicts and you cannot expect that on failure the other documents are not inserted.


When you want to remove many documents at once, use bulk remove. Returns an object with a success- and error-array.

const result = await myCollection.bulkRemove([

// > {
//   success: [RxDocument, RxDocument],
//   error: []
// }


Sometimes it can be helpful to spawn and use documents before saving them into the database. This is useful especially when you want to use the ORM methods or prefill values from form data. You can create temporary documents by calling RxCollection.newDocument(initalData).

const tempDoc = myCollection.newDocument({
    firstName: 'Bob'

// fill in data later
tempDoc.lastName = 'Kelso';
tempDoc.age = 77;

// saving a temporary document will transform it to a standard RxDocument
await tempDoc.save();


Inserts the document if it does not exist within the collection, otherwise it will overwrite it. Returns the new or overwritten RxDocument.

const doc = await myCollection.upsert({
  name: 'foo',
  lastname: 'bar2'


When you run many upsert operations on the same RxDocument in a very short timespan, you might get a 409 Conflict error. This means that you tried to run a .upsert() on the document, while the previous upsert operation was still running. To prevent these types of errors, you can run atomic upsert operations. The behavior is similar to RxDocument.atomicUpdate.

const docData = {
    name: 'Bob', // primary
    lastName: 'Kelso'

// -> throws because of parrallel update to the same document


// wait until last upsert finished
await myCollection.atomicUpsert(docData);
// -> works


To find documents in your collection, use this method. See RxQuery.find().

// find all that are older than 18
const olderDocuments = await myCollection
    .exec(); // execute


This does basically what find() does, but it returns only a single document. You can pass a primary value to find a single document more easily.

To find documents in your collection, use this method. See RxQuery.find().

// get document with name:foobar
  selector: {
    name: 'foo'
}).exec().then(doc => console.dir(doc));

// get document by primary, functionally identical to above query
  .exec().then(doc => console.dir(doc));


Find many documents by their id (primary value). This has a way better performance than running multiple findOne() or a find() with a big $or selector.

Returns a Map where the primary key of the document is mapped to the document. Documents that do not exist or are deleted, will not be inside of the returned Map.

const ids = [
  /* ... */
const docsMap = await myCollection.findByIds(ids);

console.dir(docsMap); // Map(2)

NOTICE: The Map returned by findByIds is not guaranteed to return elements in the same order as the list of ids passed to it.


Same as findByIds() but returns an Observable that emits the Map each time a value of it has changed because of a database write.


Use this function to create a json export from every document in the collection. You can pass true as a parameter to decrypt the encrypted data fields of your documents.

  .then(json => console.dir(json));

// decrypted dump
  .then(json => console.dir(json));


To import the json dump into your collection, use this function.

// import the dump to the database
  .then(() => console.log('done'));

Note that importing will fire events for each inserted document.


This method allows you to replicate data between other RxCollections, pouchdb instances or remote servers which support the couchdb-sync-protocol. Full documentation on how to use replication is here.


This method allows you to replicate data between a RxCollection and a GraphQL endpoint. Full documentation on how to use replication is here.


Removes all known data of the collection and its previous versions. This removes the documents, the schemas, and older schemaVersions.

await myCollection.remove();
// collection is now removed and can be re-created


Destroys the collection's object instance. This is to free up memory and stop all observings and replications.

await myCollection.destroy();


Returns true if the given object is an instance of RxCollection. Returns false if not.

const is = isRxCollection(myObj);

If you are new to RxDB, you should continue here

results matching ""

    No results matching ""