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

Enterprise MongoDB Compatibility Mode, MongoDB Protocol / Drivers, Connection Strings, and Authentication

Build a precise AtlasMart connection and trust-boundary model for Firestore Enterprise MongoDB compatibility: protocol-compatible drivers, database UID/ID, TLS/load-balanced connection requirements, SCRAM/OIDC authentication, IAM, and serverless ownership boundaries.

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: a familiar MongoDB URI can hide a completely different operational system

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.

AtlasMart has a small Node service that already uses the MongoDB driver. The team wants to test Firestore with MongoDB compatibility because reusing MQL and ecosystem tooling could reduce application refactoring. The dangerous shortcut is to read “MongoDB compatible” as “a managed mongod cluster.” It is not. The endpoint is Firestore Enterprise infrastructure that speaks a supported MongoDB-compatible API surface. Therefore connection topology, authentication, retries, operations, pricing, scaling, observability, and unsupported commands must be revalidated.

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

Distinguish Firestore Enterprise MongoDB compatibility from MongoDB servers, Enterprise Native Core, and Enterprise Pipeline operations.

02

Construct and audit the required connection-string options without exposing credentials.

03

Choose between SCRAM database credentials and Google Cloud OIDC/IAM identities.

04

Pin a driver version inside the currently documented support line and reject a newer unsupported major.

05

Capture handshake/tool evidence that proves connectivity without interpreting it as full workload compatibility.

2. Four terms that must not collapse into one

A Firebase project is the Firebase-facing configuration attached to a Google Cloud project. A Google Cloud project is the IAM/billing/resource container. A Firestore database is a named database resource inside that project. For MongoDB-compatible access, the database also has a system-generated UID used in the network endpoint. The user-chosen database ID and the generated UID are not interchangeable.

Thing AtlasMart example What it controls
Google Cloud/Firebase project demo-atlasmart-firestore Billing, IAM, APIs, quota/resource container
Database ID atlasmart-mongo-lab Named Firestore database resource selected by the application
Database UID generated UUID4 Part of MongoDB-compatible hostname; retrieve rather than invent
Location e.g. us-central1 Physical placement, latency/availability characteristics; cannot be casually changed later

3. Mode map: syntax is not the architecture

Firestore Enterprise can be created for Native operations or MongoDB-compatible operations. Native mode offers Core and Pipeline interfaces. MongoDB compatibility exposes MQL/BSON and supported MongoDB drivers/tools. A Node application can therefore contain two very different Firestore access paths even though both are “server code.” Do not copy Pipeline syntax, Firebase Web SDK expectations, Security Rules assumptions, or emulator behavior into the MongoDB driver path.

Path Primary interface Authorization Local/offline/realtime expectation
Mobile/Web Native Core Firebase SDK Firebase Auth + Security Rules; App Check can reduce abuse Core SDK cache/listeners per platform
Server Native Core/Pipeline Firestore server client IAM/ADC + application authorization Server request model; Pipeline has different capabilities
MongoDB compatibility MongoDB wire/API + MQL/BSON SCRAM database user mapped to IAM or Google Cloud OIDC/IAM identity Managed endpoint; do not assume mobile offline or Native listener semantics

4. Connection contract: four URI facts are architectural, not decoration

Concern Required / current behavior Why AtlasMart records it
Database mode Enterprise edition · MongoDB-compatible data access This is a distinct Enterprise operation mode, not Standard Native and not Enterprise Pipeline syntax.
Host DATABASE_UID.LOCATION.firestore.goog:443 Database UID is system-generated and distinct from the database ID.
Topology option loadBalanced=true Prevents a MongoDB driver from trying to discover a mongod/mongos topology that is not exposed.
Transport tls=true Managed endpoint requires TLS.
Retryable writes retryWrites=false Retryable writes are not supported; application idempotency still matters.
Authentication SCRAM-SHA-256 database user or Google Cloud OIDC/IAM identity Identity mechanism changes credential lifecycle and deployment design.
Security layer IAM-backed database identity for MongoDB-compatible access Do not assume Firebase Auth, Security Rules, or App Check authorize MongoDB driver traffic.

The base managed URI is mongodb://DATABASE_UID.LOCATION.firestore.goog:443/DATABASE_ID?loadBalanced=true&tls=true&retryWrites=false. With SCRAM it also carries username/password and authMechanism=SCRAM-SHA-256. In Google Cloud compute environments, supported drivers can use MONGODB-OIDC so workloads rely on short-lived Google Cloud identity rather than a long-lived database password.

SCRAM URI · optional managed lab
mongodb://USERNAME:PASSWORD@DATABASE_UID.LOCATION.firestore.goog:443/atlasmart-mongo-lab?loadBalanced=true&authMechanism=SCRAM-SHA-256&tls=true&retryWrites=false
OIDC URI · Cloud Run / Compute-style service identity
mongodb://DATABASE_UID.LOCATION.firestore.goog:443/atlasmart-mongo-lab?loadBalanced=true&tls=true&retryWrites=false&authMechanism=MONGODB-OIDC&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:FIRESTORE

5. Why the lab pins mongodb@6.21.0 instead of npm latest

At the chapter review date, Firestore documentation lists Node.js MongoDB driver 5.x and 6.x as supported. npm's latest major is already 7.x. Reproducibility therefore means pinning inside the documented compatibility range, not mechanically installing the newest major. The lab uses mongodb@6.21.0, the current 6.x tag at review time. If the support matrix changes, update the course only after running the compatibility suite.

package.json · compatibility-test toolchain
{  "type": "module",  "engines": { "node": "22.23.2" },  "dependencies": {    "mongodb": "6.21.0",    "mongoose": "8.24.4"  }}
Wrong approach: npm install mongodb@latest

Current npm latest is a newer major than the documented Firestore support line. “The driver can open a socket” is not enough; topology negotiation, auth, sessions, BSON codecs, transactions, cursors, and helper methods can change. Repair by pinning a supported major/minor, archiving the support-matrix date, and treating any upgrade as a compatibility-test event.

6. Authentication is workload identity, not end-user authorization

SCRAM creates a database user credential whose generated password is displayed once. Google Cloud OIDC uses a service account or Google Auth Library/ADC path and is usually preferable for managed workloads because credentials are short lived. Neither path automatically implements AtlasMart's customer/seller/tenant business authorization. A backend authenticated as a broad database principal must still reject a caller who asks for another tenant's data.

backend authorization remains application code
export function authorizeSeller(caller, requestedSellerId) {  if (!caller?.uid) throw new Error("UNAUTHENTICATED");  if (!caller.sellerIds?.includes(requestedSellerId)) throw new Error("FORBIDDEN");  return { tenantId: caller.tenantId, sellerId: requestedSellerId };}// Bind only trusted tenantId/sellerId values into MongoDB queries.

7. Optional managed handshake: collect evidence, not secrets

When a billed isolated project is available, retrieve the UID/location, connect with mongosh 2.10.0 or the pinned driver, run hello/buildInfo, and archive only non-secret metadata. Never print the URI if it contains a password or temporary access token. A successful handshake proves protocol/auth connectivity. It does not prove every command, ODM plugin, transaction pattern, index, or operational runbook is compatible.

managed evidence commands · optional
gcloud --versionmongosh --versiongcloud firestore databases describe \  --database=atlasmart-mongo-lab \  --format='yaml(name,locationId,uid,type,databaseEdition)'# Inside mongosh after safe authenticated connection:db.runCommand({ hello: 1 })db.runCommand({ buildInfo: 1 })

8. Mandatory no-cost lab: freeze a compatibility contract before any cloud connection

The local harness does not pretend to emulate the wire protocol. It does something more useful before credentials exist: fixes AtlasMart's dataset, required query results, and the versioned compatibility assumptions that a later real-project test must verify. This prevents “we changed three things at once” migration debugging.

atlasmart-products.json · deterministic fixture
[  {"_id":"p-1001","sellerId":"seller-a","tenantId":"tenant-a","name":"Trail Camera","category":"cameras","price":99.0,"stock":8,"rating":4.6,"tags":["outdoor","camera"],"published":true},  {"_id":"p-1002","sellerId":"seller-a","tenantId":"tenant-a","name":"USB-C Hub","category":"accessories","price":49.0,"stock":3,"rating":4.4,"tags":["usb-c","desk"],"published":true},  {"_id":"p-1003","sellerId":"seller-b","tenantId":"tenant-a","name":"Temp Sensor","category":"sensors","price":39.0,"stock":12,"rating":4.7,"tags":["iot","sensor"],"published":true},  {"_id":"p-1004","sellerId":"seller-b","tenantId":"tenant-a","name":"Edge Gateway","category":"gateways","price":149.0,"stock":1,"rating":4.2,"tags":["edge","iot"],"published":true},  {"_id":"p-1005","sellerId":"seller-c","tenantId":"tenant-b","name":"PoE Camera","category":"cameras","price":199.0,"stock":5,"rating":4.8,"tags":["poe","camera"],"published":true},  {"_id":"p-1006","sellerId":"seller-a","tenantId":"tenant-a","name":"Bench PSU","category":"power","price":89.0,"stock":9,"rating":4.5,"tags":["bench","power"],"published":true}]
compatibility-matrix.json · versioned contract
{  "target": "firestore-enterprise-mongodb-compat-2026-09-17",  "driver": "mongodb@6.21.0",  "checks": {    "find": "supported",    "insert": "supported",    "update": "supported",    "delete": "supported",    "aggregate": "supported",    "transactions": "supported-with-different-defaults",    "retryableWrites": "unsupported-disable-in-uri",    "mapReduce": "unsupported",    "gridFS": "unsupported",    "wildcardIndexes": "unsupported",    "vectorIndexMongoAPI": "unsupported",    "textSearch": "preview",    "geoNear": "preview",    "changeStreams": "preview"  }}
compatibility-local.mjs · mandatory no-credential harness
import assert from "node:assert/strict";import fs from "node:fs";const products = JSON.parse(fs.readFileSync("atlasmart-products.json", "utf8"));const matrix = JSON.parse(fs.readFileSync("compatibility-matrix.json", "utf8"));assert.equal(products.length, 6);assert.equal(new Set(products.map(p => p._id)).size, 6);assert.deepEqual(  products.filter(p => p.tenantId === "tenant-a" && p.stock < 5).map(p => p._id).sort(),  ["p-1002", "p-1004"]);assert.equal(products.filter(p => p.category === "cameras").length, 2);assert.equal(matrix.checks.retryableWrites, "unsupported-disable-in-uri");assert.equal(matrix.checks.changeStreams, "preview");console.log(JSON.stringify({fixture:"PASS", products:6, lowStock:["p-1002","p-1004"]}));
run the mandatory harness
node compatibility-local.mjs

Expected deterministic output: {"fixture":"PASS","products":6,"lowStock":["p-1002","p-1004"]}. This proves only the fixture and test oracle. It proves nothing about managed driver compatibility, latency, billing, IAM, or production query planning.

9. Failure injection: remove one connection invariant at a time

Injected mistake Expected managed symptom Diagnosis / repair
Remove loadBalanced=true Driver may attempt unsupported topology behavior / connection failure Restore load-balanced mode; Firestore endpoint is not a discoverable mongod/mongos topology.
Set retryWrites=true Retryable-write incompatibility Set false and design application idempotency explicitly.
Disable TLS Connection rejected / insecure assumption Use TLS as required.
Use driver 7.x without validation Outside documented Node driver support line Pin supported 6.x until official support + test evidence exists.
Authorize tenant only in UI Backend can query other tenants Enforce application authorization server-side and test it.

Production judgment

Choose MongoDB compatibility because the workload benefits from preserving MQL, BSON, driver APIs, and supported tools while moving to Firestore's serverless operational model—not because the team wants to avoid understanding Firestore. Before adoption, AtlasMart records driver/tool versions, authentication model, required MongoDB commands/operators, region, index policy, transaction semantics, change-stream needs, observability, cost dimensions, exit path, and every unsupported dependency.

Verification checklist and cleanup

  • Project ID, database ID, UID, and location are documented as separate values.
  • URI contains loadBalanced=true, tls=true, and retryWrites=false.
  • Driver is inside the current official support matrix.
  • No password/token/connection secret is committed or logged.
  • Business authorization exists outside database authentication.
  • Local fixture oracle passes.
  • Optional managed database is isolated, bounded, and deleted only after evidence/export needs are complete.

Bridge to Lesson 2

Connectivity is only the first gate. Lesson 2 deliberately sends values, IDs, CRUD operations, filters, updates, and aggregations through a compatibility matrix so AtlasMart can detect semantic differences before they become production data defects.

Knowledge check

  1. Why is loadBalanced=true required?
  2. Why is retryWrites=false mandatory?
  3. Does a successful hello prove drop-in compatibility?
  4. Why pin mongodb@6.21.0?
  5. Do Firebase Auth/Security Rules authorize the MongoDB driver path?
Review the answers

1. The Firestore endpoint is a managed compatibility service; the option prevents normal MongoDB topology-discovery assumptions.

2. Firestore with MongoDB compatibility does not support MongoDB retryable writes. Idempotency must be handled at the application/workflow level where required.

3. No. It proves connection/protocol/authentication, not the required query, transaction, ODM, index, or operational behavior.

4. It is within the current documented Node driver 6.x support line; the newer 7.x major is not currently listed as supported.

5. Do not assume so. MongoDB-compatible connections use database/IAM identity, and backend business authorization remains explicit.

Summary and next step

This lesson established the working contract for Enterprise MongoDB Compatibility Mode, MongoDB Protocol/Drivers, Connection Strings, and Authentication. Keep its edition/mode assumptions, trust boundary, verification evidence, and operational constraints explicit when reusing the pattern.

Next, continue to Supported BSON Types, _id Rules, Documents/Collections, MQL Query/CRUD Compatibility, and Limits.

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.