Chapter 19 · Firestore with MongoDB Compatibility: Drivers, MQL/BSON, Tools, and Serverless Differences

Behavior Differences from MongoDB: Commands, Transactions / Features, Indexing, Change Semantics, and Operational Model

Compare MongoDB and Firestore MongoDB compatibility at the semantic level: commands, read/write concerns, transactions, retryable writes, indexing, change streams, text/geospatial features, errors, scaling, observability, and operations.

Advanced · 180–240 minutesMongoDB compatibility · MQL/BSON · tools · serverless differencesNode 22.23.2 · mongodb 6.21.0 · Mongoose 8.24.4 · mongosh 2.10.0gcloud 585.0.0 · managed MongoDB-compatible database optional · local contract harness mandatoryLast reviewed: 17 September 2026

1. AtlasMart problem: the hardest migration bugs live in “almost the same” semantics

Execution and safety note

Use the Emulator Suite, a Firebase demo project, or an isolated test project for destructive, security-sensitive, billing-sensitive, migration, backup/restore, or write-heavy exercises unless the lesson explicitly marks managed verification as required. Treat shown output as expected evidence unless it is explicitly identified as captured output, and re-check current Firebase/Google Cloud edition, mode, quota, pricing, and security documentation before production execution.

By now AtlasMart can connect, round-trip BSON, run core MQL, and use common tools. The remaining risk is subtler: a transaction API exists but has different defaults; retryable writes are absent; _id uniqueness exists without an automatic ordered index; change streams exist only as a Preview feature; text/geospatial search is Preview; error codes can differ; and server operations are Firestore's responsibility rather than a mongod tuning exercise. This lesson turns those differences into explicit design constraints.

Chapter 19 reproducibility baseline · reviewed 17 September 2026

AtlasMart keeps the course-wide project identity demo-atlasmart-firestore. The mandatory compatibility harness is local/no-cost and targets Node.js 22.23.2 LTS with mongodb@6.21.0, a current Firestore-supported 6.x Node driver. Tool examples pin mongosh 2.10.0, MongoDB Compass 1.50.0, Mongoose 8.24.4, Google Cloud CLI 585.0.0, and retain Firebase CLI 15.30.0 for course continuity. The optional managed database is atlasmart-mongo-lab, Enterprise edition with MongoDB-compatible data access in an explicitly chosen supported location such as us-central1. Re-check location availability before creation.

Managed-service boundary

Unlike the Native-mode labs, current official documentation does not provide a Local Emulator Suite endpoint that emulates the MongoDB wire/API compatibility surface. Therefore the mandatory lab uses deterministic BSON/query/index/compatibility fixtures and executable contract tests without credentials. A real Firestore with MongoDB compatibility database is an optional verification layer: database creation requires an actual Google Cloud/Firebase project and billing enabled, and connection/authentication uses SCRAM or Google Cloud identity. No lesson fabricates a successful handshake, Query Explain result, billed unit count, p95/p99 latency, or tool connection that was not actually executed.

Learning outcomes

01

Compare transaction isolation/read concern/write concern semantics instead of assuming MongoDB defaults.

02

Explain why retryable writes are disabled and where application idempotency belongs.

03

Design indexes for Firestore MongoDB compatibility, including _id, multikey, unique, sparse, TTL, text, and unsupported wildcard/vector cases.

04

Treat change streams, text search, and geospatial search according to current launch stage.

05

Replace MongoDB server topology/tuning runbooks with Firestore observability, scaling, IAM, backup, and cost practices.

2. Transaction semantics: supported does not mean identical defaults

Firestore with MongoDB compatibility supports snapshot isolation and serializable transactions. The documented default uses optimistic concurrency control with snapshot isolation. Supported read concerns include snapshot, majority, and linearizable; the default is snapshot. Only w:1 and w:'majority' write concerns are supported. A transaction can run for up to 270 seconds with a 60-second idle expiration, but that limit is not a target—large transactions increase contention and failure risk.

Source assumption Firestore MongoDB compatibility AtlasMart action
Retryable writes hide transient duplicate risk Retryable writes unsupported URI sets false; write APIs get idempotency keys where external retries can repeat intent.
Default transaction semantics are whatever source MongoDB used Default is optimistic + snapshot isolation Set/test required read concern; use linearizable only when invariant needs it.
Any write concern works Only w:1 and majority supported Inventory driver defaults/configuration.
Long transaction is acceptable because hard limit is large 270s / 60s idle are ceilings Keep read/write set small; test contention and abort/retry behavior.

3. Write skew is a business-invariant problem, not a syntax problem

Snapshot isolation can allow anomalies such as write skew when two transactions read overlapping state and update disjoint documents. If AtlasMart has a strict invariant—such as “at least one active warehouse approver remains”—the test must exercise concurrent transactions and, where required, use a stronger consistency mode or model the invariant on a shared contention point. “Transaction committed” does not prove the intended invariant.

transaction invariant test shape · optional managed
// Two concurrent sessions both read shared invariant state.// Each tries to update a different document.// Assert the final invariant, not merely both commit results.// Run under the exact read concern selected for production and record retries/aborts.

4. Retryable writes are off; idempotency remains on you

Because the driver must use retryWrites=false, a network failure after a request leaves the familiar “did the write commit?” ambiguity. The service/driver can still have retry behavior in other layers, but AtlasMart cannot outsource end-to-end business idempotency. For operations with external retries, use a durable idempotency key and atomic state transition rather than “try it again and hope.”

idempotent order command shape
// Pseudocode collection design:// commandReceipts/{idempotencyKey} => {status, orderId, requestHash}// orders/{orderId} => business state// In one supported transaction, reject mismatched replay and return prior result for exact replay.

5. Indexing: no automatic _id ordered index, no wildcard index

Firestore with MongoDB compatibility does not create indexes by default. It guarantees _id uniqueness without automatically creating an ordered index on that field. Supported index forms include single-field, compound, multikey, unique, sparse, 2dsphere, text, and TTL in the current matrix, while wildcard indexes and MongoDB-compatible vector indexes are not supported. Multikey must be enabled when you create the index; it is not automatically converted based on array writes.

AtlasMart index intent
db.products.createIndex({tenantId:1, sellerId:1, price:1})db.products.createIndex({tags:1}, {multikey:true})db.products.createIndex({_id:1}) // only if ordered/range access requires it// Do not copy source wildcard indexes blindly: redesign from query inventory.
Hotspot edge

An explicit _id index can make ordered access possible, but monotonically increasing IDs may concentrate writes. Reuse Chapter 15's key-distribution reasoning.

6. TTL index is lifecycle automation, not an exact timer

MongoDB-compatible TTL indexes are supported, but Firestore TTL deletion is asynchronous—typically within about 24 hours—and managed deletes are billed. The TTL index is not used as a normal query-performance index. AtlasMart must therefore enforce “expired means unusable” in application/query logic and use TTL as cleanup, not as a precise reservation scheduler.

7. Change Streams: useful, but currently Preview

Release notes added Firestore MongoDB-compatible Change Streams in April 2026 as a Preview feature. That launch stage matters. AtlasMart does not make a Preview change stream the sole irreversible business ledger without a durability/replay plan. It tests resume behavior, duplicate/event-order assumptions, document size limitations, and failure recovery separately. The current compatibility tables can lag release notes, so the release note + dedicated current documentation is the authority for feature stage.

change-stream acceptance record
{  "feature": "MongoDB-compatible Change Streams",  "launchStage": "Preview as of 2026-09-17",  "requiredForCoreOrderCorrectness": false,  "replaySource": "orders + outbox/audit evidence",  "tests": ["insert", "update", "delete", "resume", "duplicate-tolerant handler"]}

8. Text and geospatial search: Preview is not GA

Current release notes mark MongoDB-compatible text and geospatial search as Preview. Text uses a text index and $text; geospatial search uses 2dsphere indexing and supported operators such as $near. The feature matrix still excludes many familiar MongoDB geospatial operators, and the MongoDB-compatible API does not currently advertise vector indexes. Chapter 17's Native-mode vector search is a different interface—do not transpose it into this mode.

Feature Current state Do not assume
Text search Preview Full MongoDB text-search parity, every language/index option, GA support guarantees
Geospatial Preview All geometry/query operators; current support centers on documented subset such as $near
Vector index through MongoDB API Not supported in current feature matrix Native vector-search APIs automatically appear in MongoDB compatibility
Change Streams Preview Same production maturity/behavior as every MongoDB deployment

9. Administrative commands: Firestore operates the database

Many MongoDB commands for server status, replica sets, sharding, user/role management, profiler, storage engine, or topology are unavailable because there are no mongod/mongos processes for AtlasMart to operate. Use Google Cloud IAM/database users, Cloud Monitoring, Query Insights/Explain, Firestore backups/PITR/export, and service-level scaling guidance instead.

runbook translation examples
MongoDB runbook concept     -> Firestore MongoDB-compatible replacementserverStatus / mongostat     -> Cloud Monitoring + Firestore metrics/Query Insightsreplica-set management       -> managed Firestore availability; no replica-set adminshard balancing              -> managed scaling; model to avoid hotspotsMongoDB user/role commands   -> Firestore database users + IAMprofiler                     -> Query Explain / Query Insights / logs as supportedmongod config tuning         -> data/index/query/location/client tuning

10. Errors are an API contract too

The behavior-differences documentation warns that error codes/messages may differ. Never write migration tests that require a specific source-MongoDB English error string. Assert the business category (duplicate ID, unsupported feature, unauthorized, contention/abort, invalid value), log the destination code safely, and map it to application behavior.

11. Failure injection matrix

Injection Expected lesson Repair
Turn retryWrites=true Unsupported client assumption Disable; add idempotency to business commands.
Rely on natural order Ordering divergence Explicit sort + stable tie-breaker + index.
Create source wildcard index definition Unsupported index type Derive concrete indexes from query inventory.
Use Preview change stream as sole ledger Maturity/recovery risk Keep durable source-of-truth/replay state and feature flag.
Run MongoDB server admin command Unsupported operational model Use Firestore/Google Cloud controls.

Production judgment and bridge

The correct question is not “How compatible is it overall?” but “Are the exact behaviors AtlasMart requires supported, tested, observable, and recoverable at acceptable latency/cost?” Lesson 5 converts that question into an application port with executable contract tests and a migration blocker report.

Knowledge check

  1. What transaction isolation is the documented default?
  2. Why can retryWrites=false still require idempotency?
  3. Is an ordered _id index automatic?
  4. What is the current launch stage of MongoDB-compatible Change Streams?
  5. Does MongoDB compatibility expose mongod/mongos administration?
Review the answers

1. Optimistic concurrency with snapshot isolation.

2. Network/app retries can repeat business intent, and a client may not know whether the original request committed.

3. No. _id uniqueness is guaranteed, but an ordered index must be created if the query needs it.

4. Preview as of the 17 September 2026 review.

5. No. Firestore is serverless/managed; operational controls and observability are different.

Summary and next step

This lesson established the working contract for Behavior Differences from MongoDB: Commands, Transactions/Features, Indexing, Change Semantics, and Operational Model. Keep its edition/mode assumptions, trust boundary, verification evidence, and operational constraints explicit when reusing the pattern.

Next, continue to Port a Small MongoDB Application and Build Compatibility Tests Instead of Assuming Drop-In Equivalence.

Authoritative references

Keep knowledge open

Help the academy stay free and grow.

If these tutorials save you time, a small donation supports new lessons, technical review, diagrams, examples, and long-term maintenance.

ETHEthereum / ERC-20 only
0x716c4Ab160C4B66F31a28AE2448BfF68fc3a2ef0

Send only Ethereum or ERC-20 compatible assets to this address.