MongoDB Atlas for Mobile: Indexes, Search, Real-Time Updates

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
MongoDB Atlas for Mobile: Indexes, Search, Real-Time Updates
Medium
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    743
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1159
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    562

In this article, we focus on the backend for mobile app on MongoDB Atlas, covering indexes and search. When developing a mobile catalog with 200,000 products, we encountered 3-second search delays. After implementing proper indexes and Atlas Search, response time dropped to 50 ms — a 60x improvement. This article covers setting up an Atlas cluster with a replica set, designing schemas with Mongoose, building indexes for mobile queries, implementing search via Atlas Search, and real-time updates with Change Streams. Based on real experience — over 30 mobile projects (iOS, Android, Flutter) in 5 years. MongoDB for mobile apps often requires a special approach, and we'll show how to avoid common pitfalls. Directly connecting to MongoDB from a mobile client via a native driver is bad practice: credentials in code, no authorization layer. Instead, we use Atlas, API Gateway, and Device Sync. Average API response time with properly configured indexes is 10–50 ms, which is 40–200x faster than without indexes. According to MongoDB documentation, proper indexing can reduce query time by over 90%. Cost savings on operations can reach 80%, and a typical Atlas cluster for a mobile app costs between $500 and $2,000 per month depending on scale. In one project, we reduced monthly Atlas costs from $2,500 to $500, saving $2,000 per month. Development time is reduced by 30% thanks to Atlas's ready-made solutions.

Two Usage Strategies

Choosing Between Backend API and Device Sync

Strategy 1: MongoDB as backend database. The mobile client calls an API (Node.js + Mongoose), the API works with MongoDB. Standard server architecture.

Strategy 2: Atlas Device SDK (Realm) + Atlas Device Sync. A local Realm database on the device automatically syncs with Atlas MongoDB in the cloud. Two-way synchronization without writing sync logic manually.

For most projects, the first strategy is suitable. The second is justified when complex offline requirements exist: the app must work without internet and automatically sync after reconnection. If data is not critical offline or you need custom business logic on the server, REST API with Mongoose is simpler and more flexible.

Using Atlas Data API

For simple CRUD operations without a custom backend, Atlas offers Data API — HTTP endpoints to MongoDB via HTTPS with authentication using API keys or JWT. Suitable for prototypes and simple apps. In production with custom business logic, Data API is not flexible enough — use a full-fledged backend.

API with Mongoose on Node.js

// Schema with validation
const productSchema = new Schema({
    _id: { type: String, default: () => new ObjectId().toHexString() },
    title: { type: String, required: true, maxlength: 200 },
    categoryId: { type: String, required: true, index: true },
    priceCents: { type: Number, required: true, min: 0 },
    images: [{ url: String, width: Number, height: Number }],
    tags: [{ type: String, index: true }],
    metadata: Schema.Types.Mixed,
    isActive: { type: Boolean, default: true, index: true },
    createdAt: { type: Date, default: Date.now, index: true }
}, {
    collection: 'products',
    versionKey: false
})

// Compound index for typical mobile queries
productSchema.index({ categoryId: 1, isActive: 1, createdAt: -1 })
productSchema.index({ tags: 1, isActive: 1 })

The most common mistake is forgetting index: true on fields used for filtering. Without an index, MongoDB does a collection scan — on 100K documents that's seconds instead of milliseconds. Our tests showed that a compound index on categoryId, isActive, createdAt speeds up catalog queries by 40x.

Aggregation Pipeline for Mobile API

find() with simple filters is for straightforward queries. For statistics, complex selections, or joining collections, use the aggregation pipeline:

// Catalog with product count per category
const categoriesWithCount = await Category.aggregate([
    { $match: { isActive: true } },
    {
        $lookup: {
            from: 'products',
            let: { categoryId: '$_id' },
            pipeline: [
                { $match: { $expr: { $and: [
                    { $eq: ['$categoryId', '$$categoryId'] },
                    { $eq: ['$isActive', true] }
                ]}}},
                { $count: 'total' }
            ],
            as: 'productCount'
        }
    },
    {
        $project: {
            name: 1,
            slug: 1,
            imageUrl: 1,
            productCount: { $ifNull: [{ $first: '$productCount.total' }, 0] }
        }
    },
    { $sort: { sortOrder: 1 } }
])

Atlas Search for Full-Text Search

Full-text search via Atlas Search (Lucene under the hood) is faster than regex or a text index. Fuzzy search with maxEdits:1 finds "ноутбук" when the user types "ноутьбук" — critical for mobile search due to typos on virtual keyboards.

// Atlas Search index definition (in Atlas Console or via Atlas API)
// {
//   "mappings": {
//     "fields": {
//       "title": [{ "type": "string", "analyzer": "lucene.russian" }],
//       "description": [{ "type": "string", "analyzer": "lucene.russian" }]
//     }
//   }
// }

const searchResults = await Product.aggregate([
    {
        $search: {
            index: 'product_search',
            compound: {
                must: [{
                    text: {
                        query: searchQuery,
                        path: ['title', 'description'],
                        fuzzy: { maxEdits: 1 }
                    }
                }],
                filter: [{ equals: { path: 'isActive', value: true } }]
            }
        }
    },
    { $limit: 20 },
    { $project: { title: 1, priceCents: 1, thumbnailUrl: 1, score: { $meta: 'searchScore' } } }
])

According to MongoDB Atlas documentation, an index with the lucene.russian analyzer correctly handles stemming for the Russian language, improving search relevance.

Change Streams for Real-Time Updates

MongoDB Change Streams are similar to PostgreSQL LISTEN/NOTIFY. The backend subscribes to collection changes and broadcasts events to mobile clients via WebSocket:

const changeStream = Product.watch([
    { $match: { operationType: { $in: ['insert', 'update', 'delete'] } } }
], { fullDocument: 'updateLookup' })

changeStream.on('change', (change) => {
    if (change.operationType === 'update') {
        const updatedProduct = change.fullDocument
        wsServer.broadcast(`category:${updatedProduct.categoryId}`, {
            type: 'PRODUCT_UPDATED',
            data: updatedProduct
        })
    }
})

Change Streams require a MongoDB replica set — in Atlas this is enabled by default. An alternative is Atlas Device Sync, which tracks changes and syncs them to clients automatically.

Response time comparison with and without indexes
Query type Without index With index Speedup
Search by categoryId 2.1 s 12 ms ×175
Search by tags 1.8 s 8 ms ×225
Aggregation with $lookup 3.4 s 45 ms ×75

Process of Work

  1. Requirements analysis — determine load profile, data volume, offline requirements.
  2. Schema design — model documents for mobile queries, plan indexes.
  3. Atlas setup — replication, backups, clustering.
  4. API implementation — Mongoose schemas, aggregations, Atlas Search, Change Streams.
  5. Mobile client integration — network layer, caching, error handling.
  6. Deployment and monitoring — Atlas monitoring, alerts, load testing.

What's Included

Stage Result
Analysis Architectural decision document
Design ER diagram, schema specification
Atlas setup Instance + replication + backups
Development API + client SDK
Testing Performance report
Training Documentation and 2-week support

Why Choose Us

Our team has 5+ years of experience with MongoDB Atlas, with over 30 successful mobile projects (iOS, Android, Flutter). We guarantee 99.9% SLA for the Atlas cluster and provide query optimization consultations. Configuring MongoDB Atlas, schemas, indexes, Atlas Search, and API for a mobile app takes 1 to 3 weeks. Cost is calculated individually. Get a consultation from a MongoDB engineer who has worked with App Store Review Guidelines and Google Play Console.

Contact us for a consultation on configuring MongoDB Atlas for your mobile app. Reach out for a project assessment.

How to Choose a Local Data Storage Solution (Room, Core Data, Realm, Isar)?

We've all seen the scenario: the app loses data when the network drops — and it's not just a bug, it's a failure of the use case. The user fills out a form, taps "Submit", gets a timeout, and loses everything. Or worse: data gets sent twice due to incorrect retry logic. A properly chosen and configured storage layer solves this problem once and for all. The wrong choice can cost teams months of rewriting code and up to 70% of time spent on synchronization. Our experience — 10+ years in mobile development, over 50 projects with offline storage — confirms: the storage choice determines 80% of future performance and synchronization issues.

In practice, storage selection is driven by two factors: data type and synchronization requirements, not library popularity.

Room (Android) — a wrapper over SQLite with compile-time verification of SQL queries. If a query is invalid, the build fails — better than a SQLiteException at runtime. Room integrates well with Kotlin Flow and LiveData, making reactive UI updates straightforward. The main challenge is schema migrations. @Database(version = N, exportSchema = true) with migration files in assets/databases/ is mandatory; otherwise, fallbackToDestructiveMigration() will simply delete the user's data on app update.

Core Data (iOS) — not a database, but an object graph management framework over SQLite (or XML, or in-memory). NSPersistentContainer with viewContext for reading on the main thread and newBackgroundContext() for writing is the basic setup. The trouble begins when a developer calls save() on viewContext from a background thread: EXC_BAD_ACCESS at a random moment, happens once a week, with almost nothing useful in the crash log. You must use performAndWait or perform for each context strictly on its own thread. Apple Core Data Programming Guide recommends this approach.

Realm wins where you need speed with large object sets and built-in reactivity through Results + observe(). Realm stores objects directly without ORM mapping, so reads require no deserialization. According to our measurements, Realm processes reads 2–3 times faster than Core Data for volumes over 10,000 objects. On Flutter, the Realm SDK (ex-MongoDB Realm) supports Device Sync — but that's a managed service with separate infrastructure.

Hive and Isar are Flutter-specific solutions. Hive is a key-value store, fast, simple, suitable for settings and caches. Isar is a full document-oriented database with indexes, written in Rust, compiled to native code. For Flutter apps with offline functionality, Isar is now preferred: built-in query builder with type-safe filters, transactions, watchObject/watchQuery for reactivity.

Platform Solution Reactivity Synchronization
Android Room + Flow LiveData/Flow WorkManager
iOS Core Data NSFetchedResultsController CloudKit
Flutter Isar Streams Custom / Realm Sync
Cross-platform Realm RealmResults.observe Device Sync
Flutter (simple) Hive ValueListenable None

Contact us for a free audit of your current storage and optimization recommendations — this will save you hundreds of development hours and up to 60% of server request traffic.

Why Is Offline Synchronization the Hardest Part?

Local storage itself is not complicated. The complexity lies in synchronizing with the server in the presence of conflicts.

The most common pattern is optimistic updates with rollback. The user edits a record, the UI reflects the change instantly, a background request goes to the server. If the server returns an error, we roll back the local state. Sounds simple. In practice: if the user has left the screen and returned before the rollback (which may take 3 seconds), the UX is broken. You need an explicit operation queue with states (PENDING, SYNCED, FAILED) in a separate table.

On Android, for background synchronization we use WorkManager with Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED). Don't forget setInputMerger(ArrayCreatingInputMerger::class) when batching tasks — otherwise, concurrent runs will overwrite data. A typical operation queue implementation:

class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
        val pendingOps = syncDao.getPendingOperations()
        for (op in pendingOps) {
            try {
                apiClient.send(op.payload)
                syncDao.markSynced(op.id)
            } catch (e: Exception) {
                syncDao.markFailed(op.id, e.message)
                return Result.retry()
            }
        }
        return Result.success()
    }
}

On iOS, the equivalent is BGTaskScheduler with BGProcessingTaskRequest. iOS limitations on background execution time (~30 seconds for refresh tasks) mean that synchronization must be incremental: not "sync everything," but "sync the next N records, save the cursor."

Conflicts in multi-device scenarios are resolved with one of three approaches:

  • Last-write-wins based on updated_at (simplest, loses data on concurrent edits)
  • Server-wins (client always accepts server version)
  • Three-way merge (complex, requires a common ancestor — suitable for documents)

For most B2C apps, last-write-wins with a user-level time vector is sufficient, but for collaborative editing, a CRDTs approach is needed — then look at Automerge or Yjs with mobile bindings.

How We Build the Storage Layer

The repository pattern is not optional — it's mandatory. UserRepository doesn't know where the data comes from: Room, Realm, or network. The ViewModel calls repository.getUser(id), gets a Flow/Stream, and displays data. Caching logic resides inside the repository.

For Flutter, a typical architecture: Isar for persistence, Riverpod for state management, ConnectivityPlus for network status, and a custom SyncService with an operation queue. Riverpod's AsyncNotifier conveniently covers the logic of "show cache, update from network, show new data." Example repository with caching:

class UserRepository {
  final Isar isar;
  final ApiClient api;

  Future<User> getUser(String id) async {
    // try from local storage first
    final cached = await isar.user.where().idEqualTo(id).findFirst();
    if (cached != null) return cached;
    // otherwise from network
    final remote = await api.fetchUser(id);
    // save locally
    await isar.writeTxn(() => isar.user.put(remote));
    return remote;
  }
}

Another important topic is encryption. If the app stores medical data, payment cards, or corporate documents, SQLCipher (Android) and NSFileProtection (iOS) are not optional. Realm supports encryption natively via a 64-byte key that must be stored in Keychain/Keystore, not in SharedPreferences. Skimping on security can lead to data leaks with serious consequences.

What the Work Includes

We guarantee a transparent process and document each stage:

Stage Result
Requirements audit Document analyzing data types, volumes, synchronization scenarios
Schema design ER diagram, migration files, conflict resolution plan
Repository layer development Code with unit tests (in-memory DB + network mocks)
Synchronization integration Operation queue, error handling, fallback logic
Profiling and optimization Report from Android Profiler / Core Data SQLDebug, recommendations
Deployment and documentation Deployment instructions, API description, repository access

Want to avoid common mistakes when designing storage? Contact us — we'll help design a reliable local storage from scratch or improve an existing one.

Stages of Work

We start with a requirements audit: what data, what volume, is synchronization needed, are conflicts possible. At this stage, it becomes clear whether Core Data or an SQLite-based solution is needed, whether Realm Sync is required or simple REST polling will suffice.

Next, we design the schema with migrations in mind. Schemas change in any project — the question is not "will there be migrations," but "how painful will they be." We export the schema as JSON, store it in the repository, and write tests for each version's migration.

Development includes unit test coverage for the repository layer: network layer mocks, a real in-memory database for query testing. Before release, we profile queries using Android Profiler (Database Inspector tab) or Core Data debug flags (-com.apple.CoreData.SQLDebug 1).

The implementation timeline for a storage layer with basic offline synchronization ranges from 2 to 6 weeks, depending on schema complexity and conflict resolution requirements. Contact us to get a consultation on choosing the optimal stack and migrations.