Navigation

Define Sync Rules

Overview

MongoDB Realm enforces data access rules for all requests to a synced cluster. Sync rules are dynamic JSON expressions that specify a given user’s ability to view and modify data in a synced partition.

Whenever a user opens a synced realm from a client app, Realm evaluates your app’s rules and determines if the user has read and write permissions for the partition. Users must have read permission to sync and read data in a realm and must have write permission to create, modify, or delete objects. Write permission implies read permission, so if a user has write permission then they also have read permission.

Non-Sync Rules

This page describes data access rules for synced clusters, which use a different rules model than non-synced clusters. If your app does not use sync, check out MongoDB Collection Rules for more information on rules for non-synced clusters.

Sync Rule Behavior

Sync rules apply to specific partitions and are coupled to your app’s data model by the partition key. Consider the following behavior when designing your schemas to ensure that you have appropriate data access granularity and don’t accidentally leak sensitive information.

  • Sync rules apply dynamically based on the user. One user may have full read & write access to a partition while another user has only read permissions or is unable to access the partition entirely. You control these permissions by defining JSON expressions.
  • Sync rules apply equally to all objects in a partition. If a user has read or write permission for a given partition then they can read or modify all synced fields of any object in the partition.
  • Write permissions require read permissions, so a user with write access to a partition also has read access regardless of the defined read permission rules.

Procedure

Important

You must define at least one valid schema for a collection in the synced cluster before you can define sync rules and enable sync.

At minimum, the schema must define _id and the field that you intend to use as your partition key. A partition key field may be a string, integer, or objectId.

For more details on how to define a schema, see Enforce a Document Schema.

1
2

Select a Cluster to Sync

You can enable sync for a single linked cluster in your application. Determine which cluster you want to use and then select it from the Select Cluster To Sync dropdown menu.

The cluster selection dropown menu
3

Choose a Partition Key

The sync partition key is a field in every synced document that maps each document to a client-side realm. Sync rules apply at the partition level, so it’s particularly important to consider your data model and access patterns. For more information on partition keys and how to choose one, see Partition Atlas Data into Realms.

Note

The partition key can either be required or optional. If the partition key field is optional, then all MongoDB documents that either exclude the partition key or have a null value for the partition key will be sent to the null partition. If the partition key field is required, Realm Sync ignores any MongoDB documents that lack a valid value for the partition key. We recommend a required partition key unless you want to sync pre-existing data with invalid or missing partition values from a MongoDB collection.

Once you have decided which field to use, select it from the Choose A Partition Key dropdown menu.

The partition key selection dropdown menu

Note

The partition key dropdown only lists fields defined in the cluster’s schemas that would be valid partition keys.

If you don’t see the field you want to use as the partition key listed, it probably means that your schema is invalid or that the field is not a string, integer, or objectId. You can check for schema errors on the Data Models tab of the SDKs screen.

4

Define Read & Write Permissions

The Define Permissions section allows you to define JSON expressions that Realm dynamically evaluates to determine a user’s read and write permissions for the data in a given partition.

Sync rule expressions have access to %%user, which resolves to the user that opened the realm, and %%partition, which resolves to the partition key value for the realm. You can also use operators, including %function, to handle more complex cases. For examples, see Define Sync Permissions.

Once you’ve determined how to decide a user’s read and write permissions for a given partition, define the corresponding JSON expressions in the Read and Write inputs.

The partition read and write expression inputs
5

Turn On Sync

Now that you’ve configured rules for your synced cluster, all that’s left to do is turn on sync for client applications. Click Enable Sync, take note of any recommendations that appear, and then confirm your choice.

1

Update Your Local Application

To update your app through the CLI, you need an up-to-date application directory. To export the latest version of your app, run the following command from your shell:

realm-cli export --app-id=<Your App ID>
2

Select a Cluster to Sync

You can enable sync for a single linked cluster in your application. If you have not yet linked the cluster to your application, follow the Link a MongoDB Data Source guide to link it before you continue.

Determine which cluster you want to use and then open its configuration file. Add the config.sync field with the following value:

{
  "config": {
    "sync": {
      "state": "enabled",
      "partition": {
        "key": "<Partition Key Field>",
        "type": "<Partition Key Type>",
        "permissions": {
          "read": {},
          "write": {}
        }
      }
    },
    ...
  },
  ...
}
3

Choose a Partition Key

The sync partition key is a field in every synced document that maps each document to a client-side realm. Sync rules apply at the partition level, so it’s particularly important to consider your data model and access patterns. For more information on partition keys and how to choose one, see Partition Atlas Data into Realms.

Note

The partition key can either be required or optional. If the partition key field is optional, then all MongoDB documents that either exclude the partition key or have a null value for the partition key will be sent to the null partition. If the partition key field is required, Realm Sync ignores any MongoDB documents that lack a valid value for the partition key. We recommend a required partition key unless you want to sync pre-existing data with invalid or missing partition values from a MongoDB collection.

Once you have decided which field to use, update config.sync.partition with the partition key field name in the key field and the partition key type in the type field.

{
  "config": {
    "sync": {
      "state": "enabled",
      "partition": {
        "key": "owner_id",
        "type": "string",
        "permissions": {
          "read": {},
          "write": {}
        }
      }
    },
    ...
  },
  ...
}
4

Define Read & Write Permissions

Realm allows you to define JSON expressions that it dynamically evaluates whenever a user opens a realm to determine if the user has read or write permissions for data in the partition.

Sync rule expressions have access to %%user, which resolves to the user that opened the realm, and %%partition, which resolves to the partition key value for the realm. You can also use operators, including %function, to handle more complex cases. For examples, see Define Sync Permissions.

Once you’ve determined how to decide a user’s read and write permissions for a given partition, define the corresponding JSON expressions in the read and write fields of config.sync.partition.permissions.

{
  "config": {
    "sync": {
      "state": "enabled",
      "partition": {
        "key": "owner_id",
        "type": "string",
        "permissions": {
          "read": {
            "$or": [
              { "%%user.id": "%%partition" },
              { "%%user.custom_data.shared": "%%partition" }
            ]
          },
          "write": {
            "%%user.id": "%%partition"
          }
        }
      }
    },
    ...
  },
  ...
}
5

Deploy the Sync Configuration

Now that you’ve defined the sync configuration, including read and write permissions, you can deploy your changes to start syncing data and enforcing sync rules.

To deploy your changes, import your app configuration:

realm-cli import
1

Select a Cluster to Sync

You can enable sync for a single linked cluster in your application. If you have not yet linked the cluster to your application, follow the Link a MongoDB Data Source guide to link it before you continue.

You’ll need the cluster’s service configuration file to configure sync. You can find the configuration file by listing all services through the Admin API:

curl https://realm.mongodb.com/api/admin/v3.0/groups/{GROUP_ID}/apps/{APP_ID}/services \
  -X GET \
  -h 'Authorization: Bearer <Valid Access Token>'

Once you have the configuration, add the config.sync field with the following template configuration:

{
  "config": {
    "sync": {
      "state": "enabled",
      "partition": {
        "key": "<Partition Key Field>",
        "type": "<Partition Key Type>",
        "permissions": {
          "read": {},
          "write": {}
        }
      }
    },
    ...
  },
  ...
}
2

Choose a Partition Key

The sync partition key is a field in every synced document that maps each document to a client-side realm. Sync rules apply at the partition level, so it’s particularly important to consider your data model and access patterns. For more information on partition keys and how to choose one, see Partition Atlas Data into Realms.

You can get a list of all valid partition keys and their corresponding types through the Admin API:

curl https://realm.mongodb.com/api/admin/v3.0/groups/{GROUP_ID}/apps/{APP_ID}/sync/data?service_id=<MongoDB Service ID> \
  -X GET \
  -h 'Authorization: Bearer <Valid Access Token>'

Note

The partition key can either be required or optional. If the partition key field is optional, then all MongoDB documents that either exclude the partition key or have a null value for the partition key will be sent to the null partition. If the partition key field is required, Realm Sync ignores any MongoDB documents that lack a valid value for the partition key. We recommend a required partition key unless you want to sync pre-existing data with invalid or missing partition values from a MongoDB collection.

Once you have decided which field to use, update config.sync.partition with the partition key field name in the key field and the partition key type in the type field.

{
  "config": {
    "sync": {
      "state": "enabled",
      "partition": {
        "key": "owner_id",
        "type": "string",
        "permissions": {
          "read": {},
          "write": {}
        }
      }
    },
    ...
  },
  ...
}
3

Define Read & Write Permissions

Realm allows you to define JSON expressions that it dynamically evaluates whenever a user opens a realm to determine if the user has read or write permissions for data in the partition.

Sync rule expressions have access to %%user, which resolves to the user that opened the realm, and %%partition, which resolves to the partition key value for the realm. You can also use operators, including %function, to handle more complex cases. For examples, see Define Sync Permissions.

Once you’ve determined how to decide a user’s read and write permissions for a given partition, define the corresponding JSON expressions in the read and write fields of config.sync.partition.permissions.

{
  "config": {
    "sync": {
      "state": "enabled",
      "partition": {
        "key": "owner_id",
        "type": "string",
        "permissions": {
          "read": {
            "$or": [
              { "%%user.id": "%%partition" },
              { "%%user.custom_data.shared": "%%partition" }
            ]
          },
          "write": {
            "%%user.id": "%%partition"
          }
        }
      }
    },
    ...
  },
  ...
}
4

Deploy the Sync Configuration

Now that you’ve defined the sync configuration, including read and write permissions, you can deploy your changes to start syncing data and enforcing sync rules.

To deploy your changes, send an Admin API request that updates the cluster configuration with your sync configuration:

curl https://realm.mongodb.com/api/admin/v3.0/groups/{GROUP_ID}/apps/{APP_ID}/services/{MongoDB_Service_ID}/config \
  -X PATCH \
  -h 'Authorization: Bearer <Valid Access Token>' \
  -d '{"sync":{"state":"enabled","database_name":"","partition":{"key":"_partition","type":"string","permissions":{"read":{"$or":[{"%%user.id":"%%partition"},{"%%user.custom_data.shared":"%%partition"}]},"write": {"%%user.id": "%%partition"}}}}'

Summary

  • Sync rules allow you to control who can read and write data in a given realm.
  • You can define rules in the Realm UI or by importing them with Realm CLI.