Setting Up MongoDB for Mobile App
MongoDB in mobile context usually means Atlas — cloud MongoDB with built-in mobile capabilities: Atlas Device SDK (formerly Realm), Atlas Search, Atlas Data API. Direct MongoDB connection from mobile client through native driver — not practiced for same reasons as with PostgreSQL: credentials in code, no auth layer.
Two Usage Strategies
Strategy 1: MongoDB as Backend. Mobile client calls API (Node.js + Mongoose, or Atlas App Services), API works with MongoDB. Standard backend architecture.
Strategy 2: Atlas Device SDK (Realm) + Atlas Device Sync. Local Realm database on device auto-syncs with Atlas MongoDB in cloud. Two-way sync without writing sync logic manually.
For most projects — first strategy. Second justified for complex offline-mode requirements.
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, // flexible field for extensible data
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 })
Most common mistake — forget index: true on fields filtered. MongoDB without index does collection scan — on 100K documents this is seconds instead of milliseconds.
Aggregation Pipeline for Mobile API
find() with simple filters — for simple queries. For statistics, complex selects, collection joins — aggregation pipeline:
// Catalog with product counts by categories
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 underneath) faster than regex or text index:
// Atlas Search index definition (in Atlas Console or via Atlas API)
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' } } }
])
Fuzzy search with maxEdits: 1 — finds "notebook" when searching for "notbook". For mobile search important: virtual keyboard adds typos.
Change Streams for Real-time
MongoDB Change Streams — analog of PostgreSQL LISTEN/NOTIFY. Backend subscribes to collection changes, 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 MongoDB replica set — in Atlas enabled by default.
Atlas Data API
For simple CRUD without custom backend, Atlas offers Data API — HTTP endpoints to MongoDB via HTTPS, auth via API keys or JWT. Mobile client makes REST requests directly.
Suitable for prototypes and simple apps. In production with custom business logic, Data API not flexible enough.
Setting up MongoDB Atlas, schemas, indexes, Atlas Search and API for mobile app: 1–2 weeks. Cost calculated individually.







