How To Use MongoDB In Android Studio Projects

Summarize this article with:
Your Android app needs data that syncs across devices and works offline. SQLite won’t cut it.
Learning how to use MongoDB in Android Studio gives you a cloud database solution that handles real-time sync, offline-first architecture, and document-based storage without building your own backend.
The MongoDB Realm SDK does the heavy lifting. You write Kotlin code, define data models, and let the SDK manage sync conflicts automatically.
This guide walks you through 8 steps: creating an Atlas cluster, configuring access, adding Gradle dependencies, initializing Realm, defining schemas, authenticating users, performing CRUD operations, and enabling cloud sync.
Total time: 30-45 minutes. Skill level: intermediate Android developer.
How to Use MongoDB in Android Studio
Using MongoDB in Android Studio is the process of connecting your Android app to a MongoDB Atlas cloud database through the Realm SDK.
Developers need this when building apps that require real-time data sync, offline-first architecture, or cloud-based data persistence.
This guide covers 8 steps requiring 30-45 minutes and intermediate Android development experience.
Prerequisites
Before starting, make sure you have these tools and accounts ready.
- Android Studio Electric Eel 2022.1.1 or later
- Minimum SDK: API 21 (Android 5.0 Lollipop)
- MongoDB Atlas account (free M0 tier works)
- Kotlin or Java knowledge at intermediate level
- Gradle build system familiarity
- Active internet connection
Time estimate: 30-45 minutes for complete setup.

Step One: How Do You Create a MongoDB Atlas Cluster?
Navigate to the MongoDB Atlas dashboard, select “Build a Cluster,” choose the free M0 tier, pick your preferred cloud provider region, name your cluster, and wait 3-5 minutes for provisioning to complete.
Where to Find the Cluster Creation Option
Log into MongoDB Atlas at cloud.mongodb.com.
Click Projects in the left sidebar, then Build a Cluster.
Selecting Your Cluster Configuration
Choose Shared (free tier) for development; select AWS, Google Cloud Platform, or Azure as your provider.
Pick the region closest to your target users for lower latency.
Recommended Settings for Android Apps
Cluster Tier: M0 Sandbox (free forever, 512MB storage).
Provider: Any of the three major options work fine for mobile apps.
Expected Result After Creation
Your cluster shows a green “Active” status badge within 3-5 minutes.
The connection string becomes available under the Connect button.
Why This Step Matters
The Atlas cluster serves as your Backend as a Service/) for data storage.
Without it, the Realm SDK has nowhere to sync your app’s documents.
Step Two: How Do You Configure Database Access and Network Settings?
Create a database user with read/write permissions, whitelist IP addresses for access (or allow all IPs during development), and copy your connection string URI for later use in your Android project.
Creating a Database User
Go to Security, then Database Access, then Add New Database User.
Choose password authentication and assign readWriteAnyDatabase permissions.
User Configuration Details
Username: Pick something descriptive like “androidappuser”.
Password: Generate a strong password; store it securely.
Permission Levels Explained
Read and write to any database covers most mobile application development needs.
Restrict further for production using custom roles.
Configuring Network Access Rules
Navigate to Security, then Network Access, then Add IP Address.
For development, select Allow Access from Anywhere (0.0.0.0/0).
Development vs Production Settings
Development: 0.0.0.0/0 allows any IP; convenient but less secure.
Production: Whitelist specific IPs or use VPC peering.
Security Considerations
Mobile apps connect from dynamic IPs, making strict whitelisting tricky.
Rely on token-based authentication and user permissions instead.
Why Network Configuration Matters
Connection failures often trace back to IP restrictions blocking your device.
Getting this right saves hours of debugging later.
Step Three: How Do You Add MongoDB Realm SDK Dependencies to Android Project?
Open both build.gradle files in your Android Studio project, add the Realm Kotlin SDK plugin and implementation dependency, then sync Gradle to download all required libraries.
Modifying the Project-Level build.gradle
Open the root build.gradle file (Project level).
Add the Realm plugin to your buildscript or plugins block.
Plugin Declaration
“ plugins { id("io.realm.kotlin") version "1.11.0" apply false } `
Check Maven Central for the latest version number.
Repository Configuration
Ensure mavenCentral() appears in your repositories block.
Realm SDK artifacts live there, not in Google’s repository.
Modifying the App-Level build.gradle
Open app/build.gradle and apply the plugin.
Add the implementation dependency in the dependencies block.
Required Dependencies
` plugins { id("io.realm.kotlin") }
dependencies { implementation(“io.realm.kotlin:library-sync:1.11.0”) } `
The library-sync variant includes Atlas Device Sync capabilities.
Sync and Verify
Click Sync Now when Android Studio prompts you.
Build should complete without errors if versions match.
Why Proper Dependency Setup Matters
Wrong versions or missing repositories cause cryptic build failures.
The Realm SDK handles all API integration with MongoDB Atlas automatically.
Step Four: How Do You Initialize MongoDB Realm in Your Android Application?
Create or modify your Application class, initialize the Realm App object with your Atlas App ID in the onCreate method, and register the Application class in AndroidManifest.xml to ensure initialization happens before any Activity loads.
Creating the Application Class
Right-click your main package, select New, then Kotlin Class, name it MyApplication.
Extend the Application class and override onCreate().
Basic Application Class Structure
` class MyApplication : Application() { override fun onCreate() { super.onCreate() // Realm init goes here } } `
Finding Your Atlas App ID
Atlas dashboard: App Services, then your app, then App ID in the left panel.
Looks like: “application-0-xxxxx”.
Initializing the Realm App Object
Use the App.create() method with your App ID string.
Store the App instance for access throughout your codebase.
Initialization Code
` val app = App.create("your-app-id-here") `
Consider using a companion object or dependency injection for app-wide access.
Registering in AndroidManifest.xml
Add android:name=”.MyApplication” to your application tag.
Without this, Android ignores your custom Application class entirely.
Why Global Initialization Matters
Realm needs setup before any database operations run; the Application class guarantees this timing across the entire app lifecycle.
Step Five: How Do You Define Data Models for MongoDB Realm?
Create Kotlin or Java classes that extend RealmObject, define properties with supported types, and annotate primary keys with @PrimaryKey to enable document identification and sync.
Creating a RealmObject Class
Data models map directly to MongoDB documents.
Each class becomes a collection in your database.
Basic Model Structure
` class Task : RealmObject { @PrimaryKey var id: ObjectId = ObjectId() var name: String = "" var isComplete: Boolean = false } `
Supported Property Types
- String, Int, Long, Float, Double, Boolean
- ObjectId, RealmInstant (timestamps)
- RealmList for arrays
- Embedded objects for nested data
Configuring Primary Keys
Every synced object needs a unique identifier.
ObjectId generates automatically; you can also use String or Int.
Primary Key Options
ObjectId: Auto-generated, guaranteed unique across distributed systems.
String/Int: Use when you need human-readable IDs or external system integration.
Optional vs Required Fields
Nullable types (String?) allow null values; non-null types require defaults.
Match your schema requirements in Atlas App Services.
Why Proper Data Modeling Matters
Schema mismatches between client and server cause sync failures; define models carefully before writing data.
Step Six: How Do You Authenticate Users with MongoDB Realm?
Choose an authentication provider in Atlas App Services, implement the login flow using Credentials class in your Android code, handle async callbacks for success/failure, and store the authenticated User object for subsequent operations.
Available Authentication Methods
Atlas supports multiple providers out of the box.
Anonymous auth works great for testing; switch to email/password or OAuth for production.
Provider Options
- Anonymous: No user input required
- Email/Password: Traditional registration flow
- API Keys: Server-to-server communication
- Google, Facebook, Apple: Social login integration
Enabling Providers in Atlas
App Services, then Authentication, then select provider, then toggle ON.
Configure required settings like OAuth client IDs.
Implementing Login in Android
Create credentials, call app.login(), handle the result.
Use Kotlin coroutines for cleaner async code.
Anonymous Login Code
` val credentials = Credentials.anonymous() val user = app.login(credentials) `
Email/Password Login Code
` val credentials = Credentials.emailPassword( email, password ) val user = app.login(credentials) `
Why Authentication is Required
Realm sync requires an authenticated user; following mobile app security best practices means never allowing anonymous access in production apps.
Step Seven: How Do You Perform CRUD Operations with MongoDB Realm?
Open a Realm instance with your schema configuration, use write transactions for Create/Update/Delete operations, query data using RealmQuery methods, and close the Realm instance in lifecycle callbacks to prevent memory leaks.
Opening a Realm Instance
Configure the Realm with your user and schema classes.
The instance handles local caching and cloud sync automatically.
Configuration Code
` val config = SyncConfiguration.Builder( user, setOf(Task::class) ).build() val realm = Realm.open(config) `
Sync vs Local Configuration
SyncConfiguration: Connects to Atlas, enables real-time data sync.
RealmConfiguration: Local-only storage, no cloud connection.
Write Transactions for Data Changes
All modifications require a write block.
Transactions ensure data consistency.
Create Operation
` realm.write { copyToRealm(Task().apply { name = "Buy groceries" }) } `
Update and Delete Operations
` realm.write { val task = query("id == $0", taskId) .first().find() task?.name = "Updated name" // Update task?.let { delete(it) } // Delete } `
Querying Data
Realm uses its own query language similar to NSPredicate.
Queries return live objects that update automatically.
Query Examples
` // All tasks val allTasks = realm.query().find()
// Filtered query val incomplete = realm.query( “isComplete == false” ).find() `
Closing the Realm
Call realm.close() in onDestroy() or when done.
Leaked Realm instances cause crashes and memory issues.
Why Transaction-Based Writes Matter
Atomic transactions prevent partial writes and data corruption; this pattern is standard in databases for mobile apps.
Step Eight: How Do You Enable Sync Between Local and Cloud Database?
Configure Flexible Sync or Partition-Based Sync in Atlas App Services, set up subscription queries in your Android code to define which documents sync, implement conflict resolution strategies, and monitor sync status for user feedback.
Choosing a Sync Mode
Flexible Sync: Query-based subscriptions, more granular control.
Partition-Based Sync: Simpler setup, data divided by partition key.
Enabling Sync in Atlas
App Services, then Sync, then Enable Sync.
Select Flexible for most new projects.
Defining Sync Rules
Set read/write permissions per collection.
Use expressions like “user.id == document.ownerid” for user-specific data.
Setting Up Subscriptions in Android
Subscriptions tell Realm which documents to sync locally.
Add them after opening the synced Realm.
Subscription Code
` realm.subscriptions.update { add(realm.query( "ownerid == $0", user.id ), "user-tasks") } `
Waiting for Sync
` realm.subscriptions.waitForSynchronization() `
Block until initial sync completes; show loading UI during this.
Handling Sync Conflicts
Last-write-wins is the default resolution strategy.
Custom handlers available for complex merge logic.
Why Sync Configuration Matters
Proper sync setup enables offline-first architecture; users can work without internet, and changes merge automatically when connectivity returns, creating a true cloud-based app experience.
Verification
Confirm your MongoDB integration works correctly with these checks.
Testing Local Operations
Run your app, perform a write operation, check Logcat for “Realm opened successfully” messages.
Query the data back immediately to verify persistence.
Verifying Cloud Sync
Open Atlas, go to Collections, find your database.
Documents created on device should appear within seconds.
Offline/Online Behavior
Enable airplane mode, create data, disable airplane mode.
Data should sync to Atlas automatically when connectivity returns.
Troubleshooting
Issue: Realm Initialization Fails with “Invalid App ID”
Verify App ID matches exactly from Atlas App Services.
Check for extra spaces or wrong case; the string is case-sensitive.
Issue: Network Error on Connection
Check Network Access settings in Atlas; confirm IP whitelist includes 0.0.0.0/0 for development.
Verify device has active internet connection.
Issue: Sync Not Working
Confirm Sync is enabled in Atlas App Services.
Check subscription query matches existing data; verify user authenticated before opening synced Realm.
Issue: Build Fails After Adding Dependencies
Verify Gradle version compatibility with Realm SDK version.
Run File, then Invalidate Caches, then Restart.
Issue: Schema Mismatch Errors
Local model must match Atlas schema exactly.
Delete app data or increment schema version when changing models during development.
Related Processes
Continue building your MongoDB-powered Android app with these related guides.
- How to migrate from SQLite to MongoDB Realm
- How to implement offline-first architecture in Android
- How to secure MongoDB Realm data with encryption
- How to use MongoDB aggregation pipelines in Android
- How to build Android apps with Kotlin
- How to use Android Studio
- How to build APK in Android Studio
FAQ on How To Use MongoDB In Android Studio
Can You Use MongoDB Directly in Android Apps?
Not directly. Android apps connect to MongoDB Atlas through the Realm SDK, which handles authentication, data sync, and offline caching. The SDK communicates with your cloud cluster, so you never expose database credentials in your app code.
Is MongoDB Realm Free for Android Development?
Yes. The M0 free tier provides 512MB storage, which covers most development and small production apps. Realm SDK is open source. You only pay when exceeding free tier limits on Atlas or needing advanced features like dedicated clusters.
What Is the Difference Between MongoDB and Realm?
MongoDB is the cloud database storing your documents. Realm is the mobile SDK handling local persistence, sync, and offline support. They work together: Realm syncs data between your Android app and MongoDB Atlas automatically.
How Do You Handle Offline Data with MongoDB Realm?
Realm stores data locally on the device first. Users can read and write without internet. When connectivity returns, Realm syncs changes to Atlas automatically. Conflict resolution uses last-write-wins by default, or custom handlers for complex scenarios.
Which Is Better for Android: MongoDB Realm or Firebase?
Depends on your needs. Firebase offers simpler setup and Google integration. MongoDB Realm provides more flexible queries, better offline support, and document-based storage. Choose Firebase for quick prototypes; Realm for complex data models and software scalability.
Can You Use MongoDB with Kotlin Coroutines?
Yes. The Realm Kotlin SDK supports coroutines natively. Use suspend functions for async operations like login and sync. Flow support enables reactive data streams, perfect for updating UI when database changes occur in real-time.
How Do You Secure MongoDB Connections in Android?
Never store connection strings or credentials in your app. Use Atlas App Services authentication instead. Enable mobile app security features like user-based permissions, SSL encryption, and API key rotation for production deployments.
What Happens When MongoDB Atlas Is Down?
Your app keeps working. Realm caches data locally, so reads and writes continue offline. When Atlas recovers, sync resumes automatically. This offline-first architecture means users experience no interruption during cloud outages or network issues.
How Do You Migrate from SQLite to MongoDB Realm?
Export SQLite data to JSON, create matching RealmObject models, then import records through write transactions. The Realm SDK does not provide automatic migration tools. Plan schema carefully since document-based storage differs from relational tables.
Can Multiple Users Share Data in MongoDB Realm?
Yes. Use Flexible Sync with shared partitions or query-based subscriptions. Define permissions in Atlas App Services to control who reads and writes specific documents. Common patterns include team workspaces, shared lists, and collaborative editing scenarios.
Conclusion
You now know how to use MongoDB in Android Studio from cluster creation to data synchronization.
The setup takes 30-45 minutes. After that, your app handles JSON document storage, user authentication, and sync conflicts automatically.
RealmObject classes map directly to MongoDB collections. Write transactions keep your data consistent. Flexible Sync manages what documents live on each device.
The offline-first approach means users never wait for network requests. They work locally, and the SDK syncs when connectivity allows.
Start with the free M0 tier for development. Test your data models thoroughly before production. Use subscription queries to limit what syncs to each user.
Your next step: build a sample project and watch data flow between your Android app and Atlas in real time. The mobile app development process gets faster once you master this tech stack.
- React UI Component Libraries Worth Exploring - February 10, 2026
- The Communication Gap That Kills Outsourcing Efficiency - February 10, 2026
- React Testing Libraries Every Dev Should Know - February 9, 2026







