Android Studio

How To Use MongoDB In Android Studio Projects

How To Use MongoDB In Android Studio Projects

How to use MongoDB in Android Studio now depends on a backend server, not on the sync SDK that MongoDB shipped for years. If you’re picturing the old setup where the app talked to the database directly, that path is closed.

The pattern itself is simple enough: an Android client talks to a MongoDB Atlas cluster, but only through a REST API server sitting in between. Developers build that piece in Kotlin or Java, usually as a Node.js or Ktor backend holding the actual MongoDB driver and the connection string. None of that lives inside the Android app itself.

MongoDB retired Atlas Device SDKs (the product everyone still calls Realm) on September 30, 2025, and that closed off the old direct-sync route for good (MongoDB, 2024).

What Is MongoDB Integration in Android Studio?

Most people land on this topic still expecting Realm, the MongoDB-owned mobile database that used to sync data straight from the device with barely any setup. That product is gone in practice now. What’s left is a connection where the app calls an API, the API talks to the database, and JSON comes back on the other end.

Nothing about the app talks to MongoDB directly. A backend server sits in the middle and holds the driver, so the Android side ends up making ordinary HTTP calls, nothing more exotic than that.

MongoDB itself is a NoSQL document database, one of several answers to the broader question of picking the right database for mobile apps. MongoDB acquired Realm back in 2019 and later folded it into Atlas as the Device SDKs, a product line that stopped receiving updates.

This is not a walkthrough of that old sync SDK. What you end up building instead is a fairly ordinary cloud-based app pattern, just applied to an Android client instead of a web front end.

How Does Android Studio Connect to a MongoDB Atlas Cluster?

The Android app never opens a direct line to the cluster. It sends an HTTP request to a backend server, and that server is the only thing holding the actual MongoDB driver.

  • The Android app sends a request over HTTP
  • The backend server receives it and calls MongoDB through its own driver
  • MongoDB Atlas runs the query and returns documents
  • The backend server formats the response and sends JSON back to the app

Everything the app deals with is JSON. MongoDB stores the underlying data as BSON though, a binary format built for speed rather than readability, and the conversion happens on the backend before anything reaches the phone.

Most teams expose this chain as a RESTful API, with routes like /users or /orders mapping to collections in the database. The connection string that authenticates to Atlas lives only on the server, stored as an environment variable and never anywhere inside the Android codebase.

Why does Android dominate the mobile world?

Uncover Android development statistics: market share dominance, developer opportunities, ecosystem growth, and mobile innovation trends.

Explore Android Insights →

Which MongoDB Connection Method Should You Use in Android Studio?

Right now, a backend-mediated REST API is the only method with any real future. The other three paths either crash on Android outright or don’t exist as a maintained product anymore.

MethodCurrent statusBackend requiredBest fit
REST API backendActively supported, community standardYesNew Android projects
Atlas Data APIEnd of life since September 2025NoLegacy projects only
Atlas Device SDK (Realm)End of life since September 2025No, syncs directlyExisting Realm apps, migrating away
Direct Java or Kotlin driverNot supported on AndroidNot applicableNobody, it fails at runtime

The Atlas Device SDK, formerly Realm, worked as a Backend as a Service (BaaS) layer that synced data straight from the device. MongoDB deprecated it in September 2024, and the SDK reached end of life on September 30, 2025 (MongoDB, 2024).

The Atlas Data API followed the exact same schedule. It was deprecated alongside the Device SDKs in September 2024 and hit end-of-life on that same date. MongoDB’s own API documentation now carries an end-of-life notice right on the page, and says it’s kept around only for historical reference.

Try the direct route (adding mongodb-driver-sync straight to an Android Gradle file) and you’ll hit a crash tied to a missing JNDI class. It’s a problem reported directly on MongoDB’s own community forums, so at least you’re not alone in finding it.

Quantic, a point-of-sale platform, migrated its mobile sync off Realm once MongoDB confirmed the SDK’s retirement (Couchbase, 2025).

New to ADB or just need a quick reference? Device management, file transfers, and shell commands - including adb devices, adb push/pull, and logcat - is on one page in the ADB Commands Cheat Sheet.

Building your own API integration takes more setup time than the old sync SDK did. It’s also the path that keeps working, which counts for a lot.

What Does the MongoDB Atlas Free Tier Support?

The free cluster, still commonly called M0, covers development and small production apps without asking for a credit card up front. It’s not built for a launched app carrying real traffic though.

Free tier limits, straight from MongoDB Atlas documentation:

  • Storage capacity: 512 MB
  • Maximum connections per node: 500
  • Automatic pause after 30 days of inactivity

That connection ceiling matters more than the storage cap for most Android projects. A backend that skips connection pooling can burn through 500 connections faster than you’d think.

Once an app needs automated backups or dedicated compute, the usual next step is an M10 dedicated cluster.

How to Set Up a MongoDB Atlas Cluster for an Android Project

YouTube player

None of this setup happens inside Android Studio. It all happens over in the Atlas web console, and it takes maybe ten minutes if nothing goes sideways.

  1. Create an Atlas account and deploy a free cluster on AWS, Google Cloud, or Azure
  2. Add a database user with a username, password, and scoped read and write access
  3. Add an IP access list entry for the backend server’s address, or a temporary open range during early testing only
  4. Copy the connection string and store it as an environment variable on the backend

Once those four steps are done, the cluster is reachable: a live connection string, a database user with the right permissions, and at least one IP address allowed through. That’s the whole checklist.

MongoDB Compass, the desktop GUI, is worth installing at this point too. It lets you inspect collections without writing a single query, which is nice when you just want to eyeball what actually landed in the database.

Node.js and Express or Kotlin and Ktor: Choosing a Backend for MongoDB

Both stacks reach MongoDB through an official driver, so this really comes down to team skills and deployment habits more than any technical advantage one has over the other.

Most existing tutorials default to Node.js, mostly because that pairing has the longest track record with MongoDB. Here’s what it gets you:

  • Pairs naturally with Mongoose for schema definitions
  • The largest set of existing tutorials and community answers, by a wide margin
  • Deploys easily to Render or Railway free tiers

Kotlin and Ktor solve the same problem differently. The appeal there is keeping client and server code in one language, so you’re not context-switching between Kotlin on the app side and JavaScript on the backend. Ktor leans on Kotlin coroutines for non-blocking database calls, and the tradeoff is a smaller community with fewer ready-made examples to lean on when something breaks.

Neither stack represents better back-end development, they just optimize for different priorities. Teams already comfortable in Kotlin sometimes pick Ktor purely to avoid the context switch, which is a reasonable way to settle most tech stack for app development debates.

Configuring Android Studio to Reach the MongoDB Backend

Getting the app to actually talk to the backend takes a networking library, a Gradle dependency, and a network security exception for local testing. Most of this only needs setting up once per project, and whether the project is written in Kotlin or Java, the Retrofit setup itself barely changes.

Adding the Retrofit Dependency

Retrofit handles the HTTP calls, while OkHttp sits underneath it managing the actual connections.

  • implementation com.squareup.retrofit2:retrofit
  • implementation com.squareup.retrofit2:converter-gson
  • implementation com.squareup.okhttp3:logging-interceptor

Add those three lines to the app-level Gradle build file, then sync the project before writing a single API interface. The Gson converter handles JSON response parsing on its own once it’s wired into the Retrofit builder, no extra code needed for the common cases.

If nothing happens after saving the file, the fix is almost always to sync gradle in Android Studio manually from the toolbar.

Setting the Network Security Config

Android blocks plain HTTP by default starting with API level 28, so local testing needs an explicit exception carved out.

The config file needs a cleartext traffic exception scoped to the local backend address only (never left open in production), a domain entry, usually 10.0.2.2 when the backend runs on the same machine as the emulator, and a manifest reference where a networkSecurityConfig attribute points at the new XML file.

Skipping this step is the single most common reason a Retrofit call fails silently during local testing.

How Authentication Works Between the App, the Backend and the Cluster

The Android app never sees a MongoDB password. It authenticates to the backend instead, and the backend is the only piece holding real database credentials.

There are two separate layers doing the work here:

  • App to backend: an API key or a signed token
  • Backend to Atlas: a database username and password checked against the connection string

The app-to-backend layer is usually built as token-based authentication, most often JWT. MongoDB’s own drivers default to SCRAM-SHA-256 for the second layer, the standard challenge-response mechanism Atlas uses for every database user (MongoDB documentation).

Keeping those two layers separate is basic mobile app security best practices. A leaked app binary never exposes a database password this way, which is really the whole point of splitting them.

If the backend’s outbound IP address is not on the cluster’s access list, none of this matters: authentication never even gets a chance to run.

Performing CRUD Operations From the Android App

Every operation follows the same shape: Retrofit call, Express route, MongoDB driver method, JSON back to the app.

OperationHTTP verbExpress routeEffect
InsertPOST/itemsCreates one document
ReadGET/items/:idReturns one document
UpdatePATCH/items/:idModifies matching fields only
DeleteDELETE/items/:idRemoves the document

An insert call from Retrofit sends a plain JSON body, nothing MongoDB-specific about it. The Express route just hands that body to Mongoose, which validates it against the schema before writing.

A Kotlin insert call, at a glance, comes down to building a data class that matches the JSON shape, wrapping the Retrofit call in a coroutine (network calls can’t run on the main thread), and handling the response code before you even touch the returned body.

Wrapping these calls in unit testing catches broken field mappings early. Mocking in unit tests lets you fake the backend’s response entirely too, so the tests never end up depending on a live cluster.

When MongoDB Integration in Android Studio Does Not Work

This entire approach is the wrong choice for a small app with no real backend need, and it’s worth saying plainly before you sink a weekend into it.

Single-user apps with no sync requirement across devices don’t need any of this. Neither does a project where nobody on the team actually wants to run and monitor a server long-term, or a throwaway prototype that won’t exist in a few weeks anyway.

Running a REST API backend is not a one-time setup, it’s post-deployment maintenance for as long as the app stays live.

Free hosting makes this worse in a specific way. Render’s free web services spin down after 15 minutes with no traffic and typically take somewhere from a few seconds up to roughly a minute to wake back up, depending on the app (Render, 2026). A user opening the app after it’s sat idle hits that cold start directly, with no warning screen unless someone builds one.

Add a paid backend tier plus a domain and monitoring, and the real mobile app development cost stops being zero, even though the Atlas cluster itself stays free.

The offline-first behavior Realm used to provide automatically is gone too. Any app that genuinely needs to work without a network connection has to build its own queue and conflict resolution from scratch, which is not a small undertaking.

MongoDB vs Firebase vs Room for an Android App

These three solve different problems, so the comparison is really about what the app needs, not which product is objectively better.

DatabaseModelOffline support
MongoDB (via backend)Cloud NoSQL document storeRequires a custom-built queue
Firebase Realtime DatabaseCloud NoSQL, Google-managedBuilt in, automatic
RoomOn-device wrapper over SQLiteNative, no network needed

MongoDB, through the backend setup described above, gives you full control over schema and queries, but you’re the one building and running that backend indefinitely. Firebase trades that control away for almost zero setup, a managed backend that handles most of what you’d otherwise write yourself, though it gets awkward once your queries get genuinely complex. Room sits apart from both of these since it never touches a network at all, which is great until two devices need to share the same data, at which point it’s simply the wrong tool.

Firebase’s own documentation confirms the Realtime Database keeps a local write queue automatically and syncs it once the device reconnects. Android’s own developer documentation recommends Room over raw SQLite APIs for structured local data, and Google’s Now in Android sample app uses it as the reference implementation.

None of these three is really competing for the same job, so the decision mostly comes down to how much infrastructure a team is willing to own.

Common MongoDB Connection Errors in Android Studio and How to Fix Them

Connection failures in this setup tend to repeat themselves once you’ve seen them a couple of times.

ErrorLikely causeFix
Request times outBackend’s IP is not on the Atlas access listAdd the exact outbound IP to the access list
401 or empty responseMissing or expired auth tokenReissue the token and check the request headers
Crash parsing the responseField names in the data class do not match the API’s JSONLine up field names exactly, or add a Gson annotation
Connection refused in the emulatorApp is pointed at localhost instead of the host machinePoint requests at 10.0.2.2 instead

The parsing crash is the one developers spend the most time chasing, since the stack trace points at Gson rather than at the actual mismatched field. It’s a genuinely annoying debugging session the first time it happens to you.

Keeping a short defect tracking log of which error showed up on which build saves time once more than one person touches the code.

A backend that suddenly starts rejecting requests in bulk sometimes needs API rate limiting, not a broken connection at all, worth checking before you assume the worst.

Test each fix against a single Postman request before touching the Android code, so the API and the app are never debugged at the same time.

FAQ on How To Use MongoDB In Android Studio

What Is MongoDB Atlas and How Does It Relate to a Local MongoDB Installation?

Think of Atlas as the version MongoDB Inc. runs and maintains for you, cloud-hosted, with none of the babysitting a self-managed install requires.

A local installation runs the same database engine on a developer’s own machine, with no managed backups, scaling, or IP access list, and no connection string pointing outside the network.

What Format Does MongoDB Use to Store and Return Documents, JSON or BSON?

Under the hood it’s BSON, a binary format that adds types JSON lacks, such as dates and raw binary data.

The REST API translates BSON to JSON before sending it to the Android app, since JSON is what Retrofit and Gson expect on the other end.

Should You Use Retrofit or Ktor Client on the Android Side?

Retrofit remains the default choice, backed by more tutorials, converters, and community answers than anything else out there.

Ktor Client fits better when the backend is also written in Ktor though, since request and response models can share the same Kotlin data classes across both sides.

Is MongoDB Atlas Data API Still Worth Using Now That It’s Deprecated?

No. MongoDB retired the Atlas Data API alongside Atlas Device SDKs, and new projects cannot enable it.

Existing integrations still using it should migrate to a REST API backend before the remaining infrastructure behind deprecated endpoints disappears.

How Do You Test the API Connection Before Wiring It Into the App UI?

Send the same requests through Postman first, using the backend’s live URL and headers.

A successful response there tells you the database, the Express routes, and authentication are all doing their job, which narrows any remaining bug down to the Android networking code itself.

What Android Studio Version and Minimum SDK Are Required to Follow This Setup?

Any current stable release of Android Studio works, since nothing here depends on a specific IDE version.

A minimum SDK of 21 or higher covers Retrofit and OkHttp comfortably, though most active projects now target 24 or above.

How Much Does Hosting the Backend Server Cost Alongside the Free MongoDB Tier?

The Atlas cluster itself stays free on the M0 tier.

Render and Railway both offer free backend hosting with usage limits, so a small project runs the entire stack at zero cost until real traffic demands a paid plan.

What Should You Fix First in MongoDB Integration in Android Studio?

MongoDB integration in Android Studio holds together in a fixed order. The Atlas cluster gets confirmed first, the backend server second, and the Android networking layer last, because debugging all three pieces at once hides which one actually failed.

In practice that means checking the cluster with MongoDB Compass, then the backend routes with Postman, and only then moving to the Android networking layer once the first two answer correctly. Skipping straight to Retrofit debugging before the backend has proven itself wastes the most developer hours, by a wide margin.

This order holds as long as MongoDB offers no managed replacement for the retired sync layer, a status still current through 2026.

A new backend, once wired to a working cluster, feeds naturally into assembling a news feed in Android Studio that renders the fetched documents as a scrollable list.

Bogdan Sandu

Stay sharp. Ship better code.

Every week: one curated article, one tool worth knowing, one tip you can use tomorrow. No noise, no padding.