How to Start with Mobile App if you have data in MongoDB Atlas
Hello Everyone, I am Henna :) and this is my 3rd article in the MongoDB Realm Sync series.
So far in the 2 articles, we have learned to create:
- MongoDB Realm Account
- Organizations and Projects
- Cluster Tier and Configuration
- Realm App on UI
- Google Authentication in Android App
- Sync Configuration on UI
- Partition based Sync and Development Mode
- NoteKeeper Android App with Sync
In this article, you will learn more about Sync Modes and how to implement Sync and create schemas when you already have data in MongoDB Atlas.
The post has been updated with the latest changes and more explanations.
CREATE A NEW PROJECT/ORGANIZATION
You can choose to create a new project in the same organization or a new organization and a new project.
This will you create another free M0 Cluster to link with your Realm App as only one free cluster is available per project.
Click on the dropdown on Top left, select your organization and create a new project in it. You can add other collaborators as per your use-case.
Create another M0 cluster. You can go through Article 1 if you need a reminder.
After the cluster is created, Click on ellipsis and Load Sample Dataset in your cluster as shown below
The sample data set is a great way if you are trying to learn MongoDB and its various Application services. Refer to Sample DataSets for Atlas Cluster to find out more.
Once, the dataset is loaded, click on “Browse Collections” to see the databases, collections, and documents that are loaded.
You can view all the databases that are there but for this article, you will use sample_restaurants database.
CREATE A NEW REALM APP
The next step is to create a Realm App. Please refer to Article 1 if you need a reminder.
Let’s create a restaurant app to go with our database. I opted for creating the app from scratch
Few things to keep in mind here:
Realm Applications as of now are available only with AWS. This can change when more cloud providers are added.
It is recommended to choose a Local Model and region which is the same or closer to the cluster region to mitigate Sync latencies that can happen with different providers and locations.
As I live in Ireland, I created my cluster (AWS) in Ireland region, as well as my Realm App.
After creating the app, the next step is would be to Start Sync. This time, you will choose “Generate a Schema” as you already have data in Atlas
Continue to Sync:
Selecting this option will lead to choosing a Sync Type either partition or flexible Sync and turning on Development Mode as we discussed in the previous article when we created our data models from the client-side (mobile application).
Generate a JSON Schema:
This option is selected when you already have data in Atlas. This will lead to Rules Tab where you will Add the collection you want to use for Sync and then later Generate Schema from it.
Adding New Collection
When we loaded sample data to the cluster, it added a lot of databases and collections associated with it, but Realm App is not aware of those collections until we configure them.
The recommendation is to have one database linked per Realm App and you can add as many collections you want to that one database. Here, we will add restaurants collection associated with sample_restaurants DB.
If you noticed, I did not select any permission template here, that's because the Sync permissions will be defined in the Sync Tab after we add this collection.
When Sync is enabled on a cluster, Sync Permissions take precedence over MongoDB Rules.
The next step is to review and deploy your changes. This is an important step, so whenever you save anything, you must deploy the changes after.
Generating JSON Schema
Once you add your collection, go to the Schema Tab from Top and click on “Generate Schema”
In the next step, select “just the restaurants collection”.
Next, set a size for sampling that means how many documents will be sampled to generate the schema. This step may take some time to complete.
Once complete, save the changes and Review Draft and Deploy.
Now, when you check the schema section from the left panel, the schema generated is as shown in the diagram below. If you check any other collection and/or database it asks you to configure the collection for Sync.
As mentioned before, it is recommended that you keep ONE database per Realm App but you can create multiple collections (aka table as per RDBMS) in that database.
Next, Click on Sync from the left panel and Start Syncing.
You are asked to select a Sync Type. Flexible Sync was released (22 Jan 2022) in preview mode. I will talk about Flexible Sync in the upcoming article. For this app, you will select “Partition Based“ sync. You will keep “Development Mode” Off for this.
Partition Key: Selecting a key is important. Based on the value of this key, the data gets separated into multiple realms/partitions. As you added restaurants collection for sync, you are given options to select one of the fields as a Partition Key.
The key you select here will divide the whole collection into multiple realms/partitions based on the value of the key. The good options here can be separating the data via cuisine or borough (location). Location seems like a good value so let's select “borough”. Keep the checkbox checked for “index on partition key”. With index enabled, searching becomes quick and easy.
Permissions: This is important too. How do you want the users of your app to read/write the data. For example, I would want all users to read all the location information on restaurants while they should only be allowed to write changes to only their selected restaurants or private realms.
You can also custom write the permissions in JSON format. Check Partition Strategies for more details.
After adding details, the permission template will look like below and the next step is to Enable Sync. (skip advance config)
Make sure to review the draft and deploy changes after adding details.
Now, you may see this blue notification on top for a while. This means that Sync is getting enabled. It scans all the documents in your collection to put them into respective partitions (borough).
After enabling Sync, the next step is to copy the generated Schema to the mobile application.
REALM OBJECT MODELS FOR MOBILE APPLICATION
When you generated schema after adding your collections, it also generated schema for your mobile applications.
Click on SDK from the left panel and then on Realm Object Models and you will notice three classes generated in multiple languages. For this demo, I am using Kotlin for the Android application.
Next step is to copy the generated schema to your mobile application.
Realm Cloud Schema v/s Realm Object Models
When you loaded sample_data to cluster and looked for schema, there was no collection listed. A collection is to be made aware of Realm Sync before the sync can happen. This was done by adding the collection restaurants and then generating schema for it by sampling X number of documents.
This simultaneously generated the schema to be added to the mobile app.
Restaurant Schema on Cloud:
Realm Object Model for Mobile
Few Points to Note:
- “_id” is a mandatory primary Key for MongoDB documents
- Your Client schema(mobile) can be a subset of Cloud Schema
- The field type (Required or optional) has to be the same on both Client and Cloud else it throws a Sync error
- The embedded objects in Cloud Schema are generated as multiple classes with embedded keyword true
- You will need to add
titlefield to your cloud schema for both address and grades with the same name as your class name so that the client model matches the cloud schema. (as shown in the diagram)
CREATE YOUR ANDROID APPLICATION
Now, the last part is to create your Android Application. Some of the steps will be repeated from previous tutorials, so you can take a look if you need a reminder.
The steps you need to follow in your Android Application are
- Add Realm dependencies and add Realm App Id and initiate Realm
- Add authentication provider of your choice, enable the same provider on the Realm UI whichever you select
- Add Realm Object Models that got generated above to the application. You can copy the generated classes directly into your application.
Please Note, if you change any names, or keep them different to what they are generated in the SDK Models , you will need to make changes directly in the UI (Schema tab) as well, otherwise you may get
Permission Denied Error. Also look at point 5 in previous step.
4. Add a select location screen. For simplicity, I have hard-coded 2 locations to select from, ideally keeping the focus on using data from Atlas and how can it be populated to the device.
5. Add a Restaurant List Screen to show the names and cuisines in the location selected. The code is as below:
- You create the config using the partition you received from intent extras from the previous activity
- You open the configuration asynchronously so that the processing happens in the background thread. Use a progress bar on the UI so that the user is aware loading is in progress
- Updating the list with data using Realm Recycler View
Some Screenshots are as below:
You can find the full code on the GitHub repo
Initial Commit. Contribute to hennasingh/Restaurants development by creating an account on GitHub.
To recap what you did :
- Created a project in different/same organization
- Created an M0 cluster and loaded sample data-set to it
- Created a Realm App and connect it to the Atlas cluster
- Add collection from the schema tab or you can enable Sync and go with Generate Schema option
- Add the number of documents you want to sample to generate schema for the collection and then click on Generate Schema
- The Realm Object Models will also be auto-generated to copy to mobile
- Go back to Sync from the left panel, select sync type, add partition key and permissions, and enable Sync
- Create Android Application, copy the schema, add authentication and other code, and Voila! :D
I hope you enjoyed reading the article and learned something new ❤. If you have any feedback that can help improve this article, do let me know.
In the next article, you will remove the hard-coded location options and access MongoDB directly from within the App using Query API to populate locations.
You can post questions on MongoDB Community Forums or if you are struggling with any topic, please feel free to reach out.