MongoDB for SQL developers: documents, embedding vs referencing and aggregation pipelines
The same small blog schema in Postgres and in MongoDB 9, side by side from Go: when to embed and when to reference, indexes and explain, $lookup and $group pipelines, and multi-document transactions that need a replica set.
Back in 2019 I wrote about setting up MongoDB on an EC2 instance. That post got the server running and stopped there. It never said how to actually model data in it, and coming from Postgres that is the hard part. The query syntax you pick up in an afternoon. Thinking in documents takes longer.
This is a beginner level post for people who know SQL. In this blog we will take one small blog schema, build it in Postgres and in MongoDB, and map each SQL idea to its Mongo version: tables to collections, joins to embedding or $lookup, GROUP BY to aggregation pipelines, and transactions. I used MongoDB 9.0.8, Postgres 18.7, Go 1.27.3 and the official Go driver v2.10.0. If you are still deciding whether you want a document database at all, start with SQL vs NoSQL: choosing a database by access pattern.
💻 The full code for this tutorial is on GitHub: FenixAra/tutorials/Databases/MongoDB/mongodb-for-sql-developers-documents-embedding-vs-referencing-and-aggregation-pipelines. Clone it and run each step yourself.
The schema in Postgres
Authors write posts. Posts have tags and comments. In SQL that's four tables.
CREATE TABLE authors (
id bigint PRIMARY KEY,
name text NOT NULL,
email text NOT NULL UNIQUE
);
CREATE TABLE posts (
id bigint PRIMARY KEY,
author_id bigint NOT NULL REFERENCES authors (id),
title text NOT NULL,
published_at timestamptz NOT NULL
);
CREATE INDEX ON posts (author_id, published_at DESC);
CREATE TABLE post_tags (
post_id bigint NOT NULL REFERENCES posts (id),
tag text NOT NULL,
PRIMARY KEY (post_id, tag)
);
CREATE INDEX ON post_tags (tag);
CREATE TABLE comments (
id bigserial PRIMARY KEY,
post_id bigint NOT NULL REFERENCES posts (id),
name text NOT NULL,
body text NOT NULL
);
And the query the blog home page needs: posts with a tag, newest first, with the author's name and a comment count.
SELECT p.title, a.name AS author, count(c.id) AS comments
FROM posts p
JOIN post_tags t ON t.post_id = p.id AND t.tag = 'mongodb'
JOIN authors a ON a.id = p.author_id
LEFT JOIN comments c ON c.post_id = p.id
GROUP BY p.id, a.name
ORDER BY p.published_at DESC;
title | author | comments
-------------------------------+--------------+----------
Indexes in MongoDB | Guest Writer | 1
MongoDB setup in AWS instance | Aravindhan | 2
Three joins for one page itself. Keep that result in mind, the Mongo version has to print the same thing.
Embedding vs referencing
In Mongo you decide, for each relationship, whether the child lives inside the parent document or in its own collection with an id pointing back. My rule of thumb:
Embed when the child belongs to one parent, is read together with it, and stays small. Tags fit perfectly. Comments on a small blog fit too.
Reference when the child is shared by many parents, changes on its own, or can grow without limit. Authors are shared by many posts and their email changes without the post caring, so they get their own collection.
There is a hard reason behind "stays small": a single document can't be bigger than 16 MB. A post with a few dozen comments is nowhere near that. A post that goes viral with 200,000 comments will be, and every update rewrites a bigger document. So if comments can grow without bound, put them in their own collection with a post_id, exactly like the SQL table. Some people keep the latest 10 comments embedded for the page and the full list in a separate collection. That's fine too.
In Go, the documents look like this.
type Author struct {
ID int64 `bson:"_id"`
Name string `bson:"name"`
Email string `bson:"email"`
Comments int `bson:"comment_count"`
}
type Comment struct {
Name string `bson:"name"`
Body string `bson:"body"`
At time.Time `bson:"at"`
}
type Post struct {
ID int64 `bson:"_id"`
AuthorID int64 `bson:"author_id"`
Title string `bson:"title"`
Tags []string `bson:"tags"`
PublishedAt time.Time `bson:"published_at"`
Comments []Comment `bson:"comments"`
}
Four tables became two collections, the tags table just disappeared into an array.
A small trap I hit here. My first seed data left At unset on the comments, and Mongo happily stored them as ISODate('0001-01-01T00:00:00.000Z'), Go's zero time. No error, no warning. There's no NOT NULL to save you, so validate in code or add a JSON schema validator on the collection.
Running Mongo as a replica set
One more thing before the code. See, multi-document transactions work only on a replica set or through mongos. My 2019 setup was a standalone mongod, and so is the default docker run mongo. I ran the code against a standalone first, on purpose, and the transaction failed with this:
transaction error: (IllegalOperation) Transaction numbers are only allowed on a replica set member or mongos
A single node replica set is enough for development.
docker run -d --name mongo9 -p 127.0.0.1:47017:27017 mongo:9 --replSet rs0 --bind_ip_all
docker exec mongo9 mongosh --quiet --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"localhost:27017"}]})'
docker exec mongo9 mongosh --quiet --eval 'rs.status().members[0].stateStr'
The last command should print PRIMARY after a couple of seconds. From the host, connect with directConnection=true. Otherwise the driver reads the member list, tries to reach localhost:27017, and that's the container's port, not yours. I left it off once to check, and after the timeout I got server selection error ... Type: ReplicaSetNoPrimary ... dial tcp [::1]:27017: connect: connection refused.
On an EC2 box like the one in the old post, the same thing is a replication.replSetName entry in /etc/mongod.conf plus one rs.initiate(). With access control on, read the docs on the replica set keyFile too.
Inserts, indexes and unique keys
The full program is in one main.go. Connect, insert, then create the indexes.
client, err := mongo.Connect(options.Client().ApplyURI(os.Getenv("MONGO_URI")))
check(err)
db := client.Database("blog")
authors, posts := db.Collection("authors"), db.Collection("posts")
_, err = authors.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{Key: "email", Value: 1}}, Options: options.Index().SetUnique(true)})
check(err)
_, err = posts.Indexes().CreateMany(ctx, []mongo.IndexModel{
{Keys: bson.D{{Key: "author_id", Value: 1}, {Key: "published_at", Value: -1}}},
{Keys: bson.D{{Key: "tags", Value: 1}, {Key: "published_at", Value: -1}}},
})
check(err)
The index on tags is a multikey index: Mongo adds one entry per array element. It does the job of the post_tags table and its index in one go. A unique index works like UNIQUE in SQL; inserting a second author with the same email gives a duplicate key error, and mongo.IsDuplicateKeyError(err) returned true for me.
Next question, did the tag query use the index. In Postgres you'd run EXPLAIN (there's a post on that). Mongo has an explain command.
winning plan: [FETCH IXSCAN(tags_1_published_at_-1)]
IXSCAN is an index scan, FETCH loads the documents. A COLLSCAN there would be the same warning sign as a Seq Scan on a big table. For which columns go first in a compound index, the same thinking applies as in Postgres index design: equality first, then the sort.
Getting that plan out took me two tries. I decoded the explain result into a bson.M and indexed into it, and the program panicked with interface {} is bson.D, not bson.M. In driver v2, only the top level becomes a bson.M, nested documents come back as bson.D. I switched to a small struct with just the fields I needed, which is nicer anyway.
The join as an aggregation pipeline
An aggregation pipeline is a list of stages. Each stage gets the documents from the one before. If you think of it as SQL clauses written in the order they actually run, it clicks quickly. Here is the home page query in mongosh:
db.posts.aggregate([
{ $match: { tags: "mongodb" } },
{ $sort: { published_at: -1 } },
{ $lookup: { from: "authors", localField: "author_id", foreignField: "_id", as: "author" } },
{ $unwind: "$author" },
{ $project: { _id: 0, title: 1, author: "$author.name", comments: { $size: "$comments" } } }
])
$match is the WHERE, $lookup is a left join that puts the matches in an array, $unwind flattens that array, and $project is the SELECT list. Comments are embedded so the count is just $size, no join needed. Output, from the Go version of the same pipeline:
[{"author":"Guest Writer","comments":1,"title":"Indexes in MongoDB"},
{"author":"Aravindhan","comments":2,"title":"MongoDB setup in AWS instance"}]
Same two rows as Postgres. Put $match first always so it can use the index, and keep $lookup for things like this page. If every read needs a $lookup, that relationship probably wanted to be embedded, or you wanted Postgres.
GROUP BY is $group. Posts per tag:
printAgg(ctx, posts, "posts per tag:", mongo.Pipeline{
{{Key: "$unwind", Value: "$tags"}},
{{Key: "$group", Value: bson.D{
{Key: "_id", Value: "$tags"},
{Key: "posts", Value: bson.D{{Key: "$sum", Value: 1}}},
}}},
{{Key: "$sort", Value: bson.D{{Key: "posts", Value: -1}, {Key: "_id", Value: 1}}}},
})
posts per tag: [{"_id":"mongodb","posts":2},{"_id":"aws","posts":1},{"_id":"golang","posts":1},{"_id":"postgres","posts":1}]
Transactions
Adding a comment and bumping the author's comment_count touches two documents in two collections. In SQL you'd wrap it in BEGIN/COMMIT (the isolation levels post goes deep on that). In Mongo it's a session and WithTransaction, which also retries on transient errors for you.
sess, err := client.StartSession()
check(err)
defer sess.EndSession(ctx)
_, err = sess.WithTransaction(ctx, func(ctx context.Context) (any, error) {
if _, err := posts.UpdateByID(ctx, int64(11), bson.D{{Key: "$push", Value: bson.D{
{Key: "comments", Value: Comment{Name: "kumar", Body: "Thanks", At: time.Now()}}}}}); err != nil {
return nil, err
}
return authors.UpdateByID(ctx, int64(1), bson.D{{Key: "$inc", Value: bson.D{{Key: "comment_count", Value: 1}}}})
})
On the replica set it printed transaction error: <nil> and comment_count=1. Use the ctx that the callback receives, not the outer one, otherwise the operations run outside the transaction.
Worth saying: a change to one document is always atomic, even with no transaction. If comments and their count lived in the same post document, a single $push plus $inc would be atomic on its own. Basically, good embedding removes a lot of the need for transactions.
Running it
go mod init example.com/mongoforsql
go get go.mongodb.org/mongo-driver/v2@v2.10.0
MONGO_URI='mongodb://127.0.0.1:47017/?directConnection=true' go run .
docker rm -f mongo9
If you came here from the old EC2 post, the replica set change is the one thing I'd go back and add to that server today.