MongoDB Database Design: Schema Visualization with Diagrams
For developers who have a MongoDB database and know mongosh, and need a diagram of its collections to work from or to hand to someone else.
On this page
MongoDB stores no table definitions, so a diagram of a MongoDB database has to be built from the documents. DbSchema connects to the database, reads a sample of documents from each collection, and draws each collection as a box with its fields, nested documents and arrays. Where a field holds the _id of a document in another collection, DbSchema draws a line between the two boxes.
You end up with an ER diagram of the collections, their validation rules and relations, and HTML5 documentation to share.
Free Community Edition plus a 15-day Architect trial. No signup. Windows, macOS and Linux.
Draw the diagram in DbSchema
- Choose File → New Model.
- Keep Connect to Database selected, click MongoDb, and press Connect.
- Under Method, choose a Cloud (Atlas) method for MongoDB Atlas or an On-Premise method for your own server. To use a connection string you already have, such as one from Atlas, choose Paste a JDBC URL as the Method and paste it.
- Under Where is the database running?, choose This computer, default port, or choose Remote computer or custom port and type
host:port. - Choose the Database, type the user and password if your server requires them, and press Connect.
- In the Reverse Engineer the Databases dialog, tick the databases to read and press Load.
DbSchema downloads the MongoDB JDBC driver the first time you connect. Reading the collections changes nothing in the database.
What the diagram shows
Each collection lists its fields with their types. A nested document, such as address, shows as a field of type object, with its own fields indented under it. An array of documents, such as items, shows as array[object], with the fields of those documents under it. An embedded document stays inside its parent's box. Only a field that refers to another collection becomes a line.
DbSchema doesn't read every document. By default it reads 100 documents from the start and 100 from the end of each collection, and lists every field that it finds in them. The diagram is an approximation of those documents, not a schema that MongoDB enforces. A field that appears only in documents DbSchema didn't read is missing from the diagram.
Double-click a collection's header to see its fields in Edit Collection. The Inferred ( no validation ) checkbox is ticked when DbSchema found the fields by reading documents.
To read more documents, raise Schema Scan Depth from fast to medium, which reads 300 documents from each end, or to full, which reads all of them. The setting is among the connection's parameters, and the DbSchema documentation lists the steps.
To check a collection yourself, list its fields in mongosh. In a scratch database, insert three customers whose documents differ:
use shop
db.customers.insertMany([
{ first_name: "Ana", address: { city: "Cluj" }, loyalty_points: 120 },
{ first_name: "Ben", loyalty_points: "80" },
{ first_name: "Cara" }
])
This pipeline reads up to 1,000 random documents and returns each top-level field, its BSON types, and how many documents hold it:
db.customers.aggregate([
{ $sample: { size: 1000 } },
{ $project: { field: { $objectToArray: "$$ROOT" } } },
{ $unwind: "$field" },
{ $group: { _id: "$field.k", types: { $addToSet: { $type: "$field.v" } }, documents: { $sum: 1 } } },
{ $sort: { _id: 1 } }
])
| _id | types | documents |
|---|---|---|
| _id | objectId | 3 |
| address | object | 1 |
| first_name | string | 3 |
| loyalty_points | int, string | 2 |
Only Ana has an address, so the field is optional in practice. loyalty_points is an int for Ana and a string for Ben, so db.customers.find({ loyalty_points: { $gt: 50 } }) returns Ana and misses Ben's "80". Fields inside address need the same pipeline one level down.
Validation rules
A validator is a rule, usually a $jsonSchema, that MongoDB checks on every insert and update of a collection. For example, this orders collection requires a customer_id that holds an ObjectId:
db.createCollection("orders", {
validator: { $jsonSchema: {
required: ["customer_id"],
properties: { customer_id: { bsonType: "objectId" } }
} }
})
db.orders.insertOne({ customer_id: db.customers.findOne({ first_name: "Ana" })._id })
db.orders.insertOne({ customer_id: "Ana" })
The first order, Ana's, goes in. The second holds the string "Ana" in customer_id, and MongoDB rejects it:
MongoServerError: Document failed validation
Where a collection has a validator, DbSchema reads its fields from the validator rather than from the documents, so the diagram shows the structure that MongoDB checks.
The Validator Level & Action tab of Edit Collection sets the collection's validationAction. The default, error, rejects a failing write. warn lets the write through and records the violation in the MongoDB log.
DbSchema writes validators too. Model → Create Collection adds a collection to the model, and Database → Create or Upgrade the Collection Validators into the Database writes the collections and their validators to MongoDB. While you are connected, a change that you confirm in Edit Collection reaches the database as well as the model file.
Relations between collections
MongoDB has no foreign keys. Ana's order points at her only because customer_id holds her _id. MongoDB doesn't check that value, so it can point at a deleted customer. DbSchema finds such references by value: where a field holds an ObjectId that matches the _id of a document in another collection, DbSchema draws a line.
A reference stored as a string or a number gets no line. Drag the field onto the field it refers to, such as customer_id onto the _id of customers, or choose Model → Find Virtual Relations, which matches fields by name.
These lines are virtual foreign keys, also called virtual relations. DbSchema keeps them in the model file, and MongoDB never sees them. The Relationships tab of Edit Collection lists them.
Browse related documents
The Data Explorer opens related collections side by side and follows the relations through the documents.
- Right-click the header of
customerson the diagram and choose Data Explorer. - Click the arrow icon next to the collection name and choose Cascade orders via Relationship.
- Move to another customer with the arrows under the document. The
orderspane reloads with that customer's orders.
Follow the next relation from the orders pane the same way, and the filter cascades one more level.
Share it as HTML5 documentation
Type a comment for a collection in the Comment tab of Edit Collection, and for a field in the Description column of the Fields tab. Then choose File → Export As... → HTML5/PDF Documentation, choose HTML5, and press Generate. The HTML5 documentation is one file that opens in any browser, with no server. It carries the diagram as a vector image. With Image Mouse-Over Tooltips ticked in the export dialog, the comments show when you point at a collection or a field.
Open this export of a MongoDB database:
Download DbSchema, connect it to your MongoDB database and import the collections: the diagram is drawn before you have typed anything. The free Community Edition connects, reads the collections, draws the diagram with its relations, and exports HTML5 documentation of a diagram with up to 12 collections. DbSchema Pro saves the model file, and with it the virtual relations you drew. It also follows relations in the Data Explorer and documents diagrams of any size.