Navigation

Access Custom User Data

Overview

You can read arbitrary data about your application users, known as custom user data, directly within your Android application. For example, you might store a user’s preferred language, date of birth, or local timezone. To learn more about custom user data, see Enable Custom User Data.

Note

To use custom user data, you must Enable Custom User Data.

Read Custom User Data

You can read the custom user data of a currently logged in user through that user’s User object. You cannot edit custom user data through a User object. To edit custom user data, see Update Custom User Data. To access the data, call the User.customData() method on the User object of a logged in user:

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
       .build())

val anonymousCredentials: Credentials = Credentials.anonymous()

val user: User? = null
app.loginAsync(anonymousCredentials) {
   if (it.isSuccess) {
       Log.v(TAG, "Successfully authenticated anonymously.")
       user = app.currentUser()
       val customUserData : Document? = user?.customData
   } else {
       Log.e(TAG, it.error.toString())
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

Credentials anonymousCredentials = Credentials.anonymous();

app.loginAsync(anonymousCredentials, it -> {
   if (it.isSuccess()) {
      Log.v(TAG, "Successfully authenticated anonymously.");
      user = app.currentUser();
      Document customUserData = user.getCustomData()
   } else {
      Log.e(TAG, it.getError().toString());
   }
});

Custom Data May Be Stale

MongoDB Realm does not dynamically update the value of User.customData() immediately when underlying data changes. Instead, MongoDB Realm fetches the most recent version of custom user data whenever a user refreshes their access token, which occurs during most SDK operations that contact the MongoDB Realm back end. Realm refreshes access tokens every 30 minutes, so custom user data can be stale for no more than 30 minutes.

Note

If you require the most recent version of custom user data, use the User.refreshCustomData() method to request the latest version of a user’s custom data.

Write Custom User Data

To create, update, or delete custom user data, you will need the following information from your custom user data configuration:

You can find this information in the the Custom User Data tab of the Users left sidebar entry of the Realm UI.

Create Custom User Data for a User

To create custom user data for a user, create a MongoDB document in the custom user data collection. The user ID field of the document should contain the the user’s user ID. The following example uses MongoDB Data Access to insert a document containing the user ID of the currently logged in user and a favoriteColor value into the custom user data collection:

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
       .build())

val anonymousCredentials: Credentials = Credentials.anonymous()

val user: User? = null
app.loginAsync(anonymousCredentials) {
   if (it.isSuccess) {
       user = app.currentUser()

       val mongoClient : MongoClient =
           user.getMongoClient("<mongodb service name for custom user data cluster>")!!
       val mongoDatabase : MongoDatabase =
           mongoClient.getDatabase("<custom user data database>")!!
       val mongoCollection : MongoCollection<Document> =
           mongoDatabase.getCollection("<custom user data cluster>")!!

       mongoCollection.insertOne(
           Document("<user ID field>", user.id).append("favoriteColor", "pink"))
           .getAsync() {
               if (it.isSuccess) {
                   Log.v("EXAMPLE", "Inserted custom user data document. _id of inserted document: ${it.get().insertedId}")
               } else {
                   Log.e("EXAMPLE", "Unable to insert custom user data. Error: ${it.error}")
               }
       }
   } else {
       Log.e("EXAMPLE", "Failed to log in anonymously: ${it.error}")
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
       .build());

Credentials credentials = Credentials.anonymous();

app.loginAsync(credentials, it -> {
   if (it.isSuccess()) {
       User user = app.currentUser();

       MongoClient mongoClient =
           user.getMongoClient("<mongodb service name for custom user data cluster>");
       MongoDatabase mongoDatabase =
           mongoClient.getDatabase("<custom user data database>");
       MongoCollection<Document> mongoCollection =
           mongoDatabase.getCollection("<custom user data cluster>");

       mongoCollection.insertOne(
           new Document("<user ID field>", user.getId()).append("favoriteColor", "pink"))
           .getAsync(result -> {
               if (result.isSuccess()) {
                   Log.v("EXAMPLE", "Inserted custom user data document. _id of inserted document: "
                       + result.get().getId());
               } else {
                   Log.e("EXAMPLE", "Unable to insert custom user data. Error: " + result.getError());
               }
       });
   } else {
       Log.e("EXAMPLE", "Failed to log in anonymously:" + it.getError().toString())
   }
}

You can add any number of arbitrary fields and values to the custom user data document when you create it. The user ID field is the only requirement for the document to become available on the User object as custom user data.

Update Custom User Data for a User

You can update custom user data using MongoDB Data Access, Realm Sync, MongoDB Compass, or the MongoDB Atlas Data Explorer.

To update a user’s custom user data with MongoDB Data Access, edit the MongoDB document whose user ID field contains the user ID of the user. The following example uses MongoDB Data Access to update the favoriteColor field of the the document containing the user ID of the currently logged in user in the custom user data collection:

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
       .build())

val anonymousCredentials: Credentials = Credentials.anonymous()

val user: User? = null
app.loginAsync(anonymousCredentials) {
   if (it.isSuccess) {
       user = app.currentUser()

       val mongoClient : MongoClient =
           user.getMongoClient("<mongodb service name for custom user data cluster>")!!
       val mongoDatabase : MongoDatabase =
           mongoClient.getDatabase("<custom user data database>")!!
       val mongoCollection : MongoCollection<Document> =
           mongoDatabase.getCollection("<custom user data cluster>")!!

       mongoCollection.updateOne(
           Document("<user ID field>", user.id), Document("favoriteColor", "cerulean"))
           .getAsync() {
               if (it.isSuccess) {
                   if (it.get().modifiedCount == 1L) {
                       Log.v("EXAMPLE", "Updated custom user data document.")
                   } else {
                       Log.v("EXAMPLE", "Could not find custom user data document to update.")
                   }
               } else {
                   Log.e("EXAMPLE", "Unable to update custom user data. Error: ${it.error}")
               }
       }
   } else {
       Log.e("EXAMPLE", "Failed to log in anonymously: ${it.error}")
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
       .build());

Credentials credentials = Credentials.anonymous();

app.loginAsync(credentials, it -> {
   if (it.isSuccess()) {
       User user = app.currentUser();

       MongoClient mongoClient =
           user.getMongoClient("<mongodb service name for custom user data cluster>");
       MongoDatabase mongoDatabase =
           mongoClient.getDatabase("<custom user data database>");
       MongoCollection<Document> mongoCollection =
           mongoDatabase.getCollection("<custom user data cluster>");

       mongoCollection.updateOne(
           new Document("<user ID field>", user.getId()), new Document("favoriteColor", "cerulean"))
           .getAsync(result -> {
               if (result.isSuccess()) {
                   if (result.get().getModifiedCount() == 1L) {
                       Log.v("EXAMPLE", "Updated custom user data document.");
                   } else {
                       Log.v("EXAMPLE", "Could not find custom user data document to update.");
                   }
               } else {
                   Log.e("EXAMPLE", "Unable to update custom user data. Error: " + result.getError().toString());
               }
       });
   } else {
       Log.e("EXAMPLE", "Failed to log in anonymously:" + it.getError().toString())
   }
}

You can determine the id of a user through either the User object of the user once logged in or via the Users tab of the Users left sidebar entry of the Realm UI.

Summary

  • You can use custom user data to store arbitrary information about your application users.
  • MongoDB Realm stores custom user data as a document in a MongoDB collection determined by your application configuration.
  • MongoDB Realm associates custom user data with a user based on the value of the user ID field.
  • The custom user data field of the user object is read-only. You can modify custom user data using MongoDB Data Access or Sync.