How to Integrate SQLAlchemy and MongoDB Safely

Published
Length
3 min read

Luis Felipe Dias

All posts

Teams use sqlalchemy and mongodb together in Python apps that need both tables and documents. SQLAlchemy handles relational tables while a native driver manages document collections in the same service. SQLAlchemy targets relational databases, so it does not run native document queries on its own. Instead, developers pair it with a document driver or a third-party dialect wrapper. This setup lets one backend service process structured transactions alongside flexible JSON records. You must secur

Your coding agents run with your access.

Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.

Teams use sqlalchemy and mongodb together in Python apps that need both tables and documents. SQLAlchemy handles relational tables while a native driver manages document collections in the same service.

SQLAlchemy targets relational databases, so it does not run native document queries on its own. Instead, developers pair it with a document driver or a third-party dialect wrapper. This setup lets one backend service process structured transactions alongside flexible JSON records. You must secure both database paths to protect sensitive records in production.

How data and roles flow between sqlalchemy and mongodb

In a dual-database Python app, each database engine manages its own pool of network sessions. SQLAlchemy opens sessions to the relational store using a database user and password. At the same time, the document client logs in to the document store. Both clients run inside the same app process and share memory.

A single web request often triggers reads or writes across both storage engines. For example, an app might check an order in SQL and save a log document. Because the app holds keys for both stores, a flaw in one path risks everything. You must lock down the permissions for each database account.

MongoDB controls access through role-based rules that allow specific actions on defined resources. A role applies to its home database and can scope access down to one collection. Note that Atlas database users have different built-in roles than self-hosted users. Still, both setups use the same basic privilege actions.

When a service only needs to fetch documents, assign it the built-in read role. The read role allows reading all non-system collections and the system JavaScript collection. It grants actions like find, listCollections, listIndexes, dbStats, collStats, and changeStream. It blocks insert, update, remove, and dropCollection actions.

If the Python worker must change document data, it needs the readWrite role instead. The readWrite role includes all read actions plus the power to change data. Its extra actions include insert, update, remove, createCollection, createIndex, dropIndex, and dropCollection. Scoping each app worker to the smallest role limits damage if a key leaks.

Common failure modes in dual-database Python apps

The biggest risk in dual-database apps is using one shared admin account for everything. Teams often put a root database string into a shared config file for speed. If an attacker reads that file, they can drop tables and collections right away. Even without an attack, a bad script can wipe out production records by mistake.

MongoDB Authentication & Authorization + End-to-End Encryption: architecture patterns and best practices

Continue reading? Get the full guide.

Free. No spam. Unsubscribe anytime.

Broad roles also cause trouble when developers run ad-hoc checks from local machines. An engineer might load the app models in a local shell to fix a bug. If their local key has full write rights, one typo can break live data. Separate keys for read-only checks and live app writes stop these mistakes.

Another common gap is missing query logs across the two database paths. When an incident happens, security teams need to know who ran which command and when. Shared service accounts hide the real person behind a generic app user name. You should tie human database sessions to individual team identities instead of static keys.

Unfiltered query results can also expose private customer details during routine debugging. Production records often hold emails, phone numbers, card numbers, or national IDs. When engineers inspect live rows or documents, data masking can rewrite matched fields in results. This keeps sensitive values off local screens while still letting teams fix code bugs.

Scoping network paths and permissions in production

Start by splitting your app into distinct services or workers based on their data needs. Give reporting workers a relational user with select rights and the MongoDB read role. Give transaction workers write rights only on the exact tables and collections they update. Never let a basic web worker hold rights to drop collections or change indexes.

Next, lock down the network paths so databases reject traffic from unknown hosts. Place both databases in private subnets that block public internet traffic by default. Rotate database keys on a regular schedule and remove static passwords from developer laptops.

Check MongoDB commands and documents on the wire

MongoDB roles and SCRAM login decide who opens a session. They do not check single commands or redact sensitive fields inside returned documents. With hoop.dev, you run an open-source proxy, a sidecar for your MongoDB. It reads the MongoDB wire protocol and checks commands and bulk writes as JSON while passing login through untouched.

Before a command runs, hoop.dev guardrails check its effect and refuse banned drops or writes with MongoDB error code 13. On the way back, hoop.dev data masking rewrites sensitive fields in returned documents that match your rules. Every command and verdict is logged. See the open-source code on GitHub.

Frequently asked questions

Can SQLAlchemy query MongoDB directly without extra tools?

No, SQLAlchemy is built for relational databases that use SQL tables. To use it with MongoDB, you run a document driver alongside it or use a SQL wrapper.

What MongoDB role should a read-only Python reporting app use?

Assign the built-in read role on the target database. It allows actions like find and listCollections while blocking insert, update, remove, and dropCollection.

How can teams protect private data when debugging both databases?

Remove static admin keys from laptops and link database sessions to individual user logins. Use data masking to rewrite emails, phone numbers, and card numbers in query results.

The query runs. The emails stay hidden.